selenium自动化测试工具python笔试面试项目实战5键盘操作

说明

本文参考答案基于Chrome,分辨率1920*1080,在其他环境表现可能会不同。
本文代码地址

  • 参考书籍下载:

Learning Selenium Testing Tools with Python-2014.pdf

Selenium自动化测试 基于 Python 语言 - 2018.pdf

上机实操: 在新的TAB打开连接

  • 打开:https://china-testing.github.io/
  • 选择"数据分析"栏目的文章
  • 按住"Ctrl+TAB"选择"python"栏目的文章
  • 切换到新的标签"python"
  • 关闭新的标签"python"
  • 关闭浏览器

参考答案

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 讨论钉钉免费群21745728 qq群144081101 567351477
# CreateDate: 2018-10-17
import time

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys


driver = webdriver.Chrome()
driver.get("https://china-testing.github.io/")
driver.implicitly_wait(30)
driver.maximize_window()
element = driver.find_element_by_link_text('数据分析')
element.click()
time.sleep(3)
element = driver.find_element_by_link_text('python')
ActionChains(driver).key_down(Keys.CONTROL).click(element).key_up(
    Keys.CONTROL).perform()
time.sleep(3)
driver.switch_to.window(driver.window_handles[1])
time.sleep(3)
driver.close() # 关闭当前TAB
time.sleep(3)
driver.quit()                                                                                            
  • 面试问答
  1. driver.quit() 和 driver.close()有什么区别?

2.selenium中按下和松开键如何表示?

3.简述ActionChains类的作用?

上机实操: 基于坐标移动

图片.png

参考答案

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 讨论钉钉免费群21745728 qq群144081101 567351477
# CreateDate: 2018-10-20
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("http://guidebook.seleniumacademy.com/Selectable.html")
driver.implicitly_wait(30)
driver.maximize_window()
one= driver.find_element_by_name('one')
print(one.location)
print(one.size)
six = driver.find_element_by_name('six')
print(six.location)
print(six.size)
actions = ActionChains(driver)
actions.move_by_offset(one.size['width'] + one.location['x'],
                       one.size['height'] + one.location['y']).click().perform()
input('Press ENTER to close the automated browser')
driver.quit()                                                                                    
  • 面试问答
  1. 如果获取元素的位置信息和大小?

2.move_by_offset()有什么作用?

上机实操: 发送delete键在google drive上删除文件

  • 准备能访问google drive,并在firefox上保存了登录的账号。
  • 打开:https://drive.google.com
  • 点击第一个文件,进行删除
  • 按上述步骤循环删除所有文件
图片.png

参考答案

# -*- coding: utf-8 -*-
# 讨论钉钉免费群21745728 qq群144081101 567351477
# CreateDate: 2018-10-20
 
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

fp = webdriver.FirefoxProfile(r'C:\Users\acer\AppData\Roaming\Mozilla\Firefox\Profiles\ar8m1pr8.default')
driver = webdriver.Firefox(fp)
driver.get("https://drive.google.com")
driver.implicitly_wait(20)
driver.maximize_window()

elements = driver.find_elements_by_xpath("//div[3]/span")
while elements:
    ActionChains(driver).click(elements[0]).send_keys(Keys.DELETE).perform()
    elements = driver.find_elements_by_xpath("//div[3]/span")
    
input('Press ENTER to close the automated browser')
driver.quit()                                                                          
  • 面试问答
  1. 如果找到实际打开浏览器默认的firebox profile?

2.如何发送DELETE键?

上机实操: 验证悬浮提示内容

图片.png
  • 鼠标移动到上图的"Your age:"
  • 确认悬浮提示内容为'We ask for your age only for statistical purposes.'
  • 关闭浏览器
  • 参考答案
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 讨论钉钉免费群21745728 qq群144081101 567351477
# CreateDate: 2018-10-17
import unittest
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.action_chains import ActionChains


class ToolTipTest (unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get("http://jqueryui.com/tooltip/")
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

    def test_tool_tip(self):
        driver = self.driver

        frame_elm = driver.find_element_by_class_name('demo-frame')
        driver.switch_to.frame(frame_elm)
        
        time.sleep(3)
        age_field = driver.find_element_by_id('age')
        ActionChains(self.driver).move_to_element(age_field).perform()

        time.sleep(3)
        tool_tip_elm = WebDriverWait(self.driver, 10).until(
            expected_conditions.visibility_of_element_located((
                By.CLASS_NAME, 'ui-tooltip-content')))

        # verify tooltip message
        self.assertEqual('We ask for your age only for statistical purposes.', 
                         tool_tip_elm.text)
        time.sleep(3)

    def tearDown(self):
        self.driver.close()

if __name__ == '__main__':
    unittest.main(verbosity=2)                                                                                      
  • 面试问答

1.move_to_element()有什么用途?

上机实操: 双击改变颜色

图片.png
  • 双击上图蓝色的框,把颜色该变成黄色
  • 参考答案
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 讨论钉钉免费群21745728 qq群144081101 567351477
# CreateDate: 2018-10-18

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import unittest


class DoubleClickTest (unittest.TestCase):

    URL = 'http://api.jquery.com/dblclick/'

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get(self.URL)
        self.driver.maximize_window()

    def test_double_click(self):
        driver = self.driver
        frame = driver.find_element_by_tag_name('iframe')
        driver.switch_to.frame(frame)
        box = driver.find_element_by_tag_name('div')

        # verify color is Blue
        self.assertEqual('rgba(0, 0, 255, 1)',
                         box.value_of_css_property('background-color'))

        ActionChains(driver).move_to_element(
            driver.find_element_by_tag_name('body')).perform()
        ActionChains(driver).double_click(box).perform()

        # verify Color is Yellow
        self.assertEqual('rgba(255, 255, 0, 1)',
                         box.value_of_css_property('background-color'))

    def tearDown(self):
        self.driver.close()

if __name__ == '__main__':
    unittest.main(verbosity=2)

  • 面试问答

1.double_click()有什么用途?

2.rgba的含义?

上机实操: 在新的TAB打开连接

图片.png
  • 拖动左边的框到右边

参考答案

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 讨论钉钉免费群21745728 qq群144081101 567351477
# CreateDate: 2018-10-18
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import unittest


class DragAndDropTest (unittest.TestCase):

    URL = 'http://jqueryui.com/resources/demos/droppable/default.html'

    def setUp(self) :
        self.driver = webdriver.Chrome()
        self.driver.get(self.URL)
        self.driver.maximize_window()

    def test_drag_and_drop(self):
        driver = self.driver

        source = driver.find_element_by_id('draggable')
        target = driver.find_element_by_id('droppable')

        ActionChains(self.driver).drag_and_drop(source, target).perform()
        self.assertEqual('Dropped!', target.text)

    def tearDown(self):
        self.driver.close()

if __name__ == '__main__':
    unittest.main(verbosity=2)

  • 面试问答

1.drag_and_drop()有什么用途?

selenium 上机实操: 下拉刷新框中所有内容(实现)

图片.png

参考答案

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# 讨论钉钉免费群21745728 qq群144081101 567351477
# CreateDate: 2018-10-18

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

class at_least_n_elements_found(object):
    def __init__(self, locator, n):
        self.locator = locator
        self.n = n
        
    def __call__(self, driver):
        elements = driver.find_elements(*self.locator)
        if len(elements) >= self.n:
            return elements
        else:
            return False
        
url = 'http://www.webscrapingfordatascience.com/complexjavascript/'
driver = webdriver.Chrome()
driver.get(url)
# Use an implicit wait for cases where we don't use an explicit one
driver.implicitly_wait(10)
div_element = driver.find_element_by_class_name('infinite-scroll')
quotes_locator = (By.CSS_SELECTOR, ".quote:not(.decode)")

nr_quotes = 0
while True:
    
    # Scroll down to the bottom, now using action (chains)
    action_chain = ActionChains(driver)
    # Move to our quotes block
    action_chain.move_to_element(div_element)
    # Click it to give it focus
    action_chain.click()
    # Press the page down key about 10 ten times
    action_chain.send_keys([Keys.PAGE_DOWN for i in range(10)])
    # Do these actions
    action_chain.perform()
    
    # Try to fetch at least nr_quotes+1 quotes
    try:
        all_quotes = WebDriverWait(driver, 3).until(
            at_least_n_elements_found(quotes_locator, nr_quotes + 1))
    except TimeoutException as ex:
        # No new quotes found within 3 seconds, assume this is all there is
        print("... done!")
        break
    
    # Otherwise, update the quote counter
    nr_quotes = len(all_quotes)
    print("... now seeing", nr_quotes, "quotes")
    
# all_quotes will contain all the quote elements
print(len(all_quotes), 'quotes found\n')
for quote in all_quotes:
    print(quote.text)
input('Press ENTER to close the automated browser')
driver.quit()
  • 面试问答

1.如何模拟鼠标中键下滚?

参考资料

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容