欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Selenium自动化测试中的键盘事件

程序员文章站 2022-06-06 18:32:27
...

我们在做Web UI自动化测试过程中而一些特殊场景需要操作鼠标或键盘进行特殊操作,如:鼠标左、右点击,键盘F5、CTRL+C、CTRL+V,小键盘、等等键盘中年的一些按键…

那么我们就会用到Keys类,Keys类提供了几乎键盘上的所有按键的方法,在前面的博文中有了解到,send_keys()可以用来模拟键盘输入的操作,除此之外,
我们还可以用Keys来模拟键盘上的按键,或者组合键,如Ctrl + C、Ctrl + V等等。

使用Keys类之前需要先导入Keys类,导入方法如下:
from selenium.webdriver.common.keys import Keys
复制代码

我们看下Keys类的源码:
class Keys(object):
“”"
Set of special keys codes.
“”"

NULL = '\ue000'
CANCEL = '\ue001'  # ^break
HELP = '\ue002'
BACKSPACE = '\ue003'
BACK_SPACE = BACKSPACE
TAB = '\ue004'
CLEAR = '\ue005'
RETURN = '\ue006'
ENTER = '\ue007'
SHIFT = '\ue008'
LEFT_SHIFT = SHIFT
CONTROL = '\ue009'
LEFT_CONTROL = CONTROL
ALT = '\ue00a'
LEFT_ALT = ALT
PAUSE = '\ue00b'
ESCAPE = '\ue00c'
SPACE = '\ue00d'
PAGE_UP = '\ue00e'
PAGE_DOWN = '\ue00f'
END = '\ue010'
HOME = '\ue011'
LEFT = '\ue012'
ARROW_LEFT = LEFT
UP = '\ue013'
ARROW_UP = UP
RIGHT = '\ue014'
ARROW_RIGHT = RIGHT
DOWN = '\ue015'
ARROW_DOWN = DOWN
INSERT = '\ue016'
DELETE = '\ue017'
SEMICOLON = '\ue018'
EQUALS = '\ue019'

NUMPAD0 = '\ue01a'  # number pad keys
NUMPAD1 = '\ue01b'
NUMPAD2 = '\ue01c'
NUMPAD3 = '\ue01d'
NUMPAD4 = '\ue01e'
NUMPAD5 = '\ue01f'
NUMPAD6 = '\ue020'
NUMPAD7 = '\ue021'
NUMPAD8 = '\ue022'
NUMPAD9 = '\ue023'
MULTIPLY = '\ue024'
ADD = '\ue025'
SEPARATOR = '\ue026'
SUBTRACT = '\ue027'
DECIMAL = '\ue028'
DIVIDE = '\ue029'

F1 = '\ue031'  # function  keys
F2 = '\ue032'
F3 = '\ue033'
F4 = '\ue034'
F5 = '\ue035'
F6 = '\ue036'
F7 = '\ue037'
F8 = '\ue038'
F9 = '\ue039'
F10 = '\ue03a'
F11 = '\ue03b'
F12 = '\ue03c'

META = '\ue03d'
COMMAND = '\ue03d'

复制代码

Keys类定义了很多成员变量,这些变量就是我们要使用到的键盘事件的发起者!那么如何实现呢?
比如我我们还是要在输入框输入内容,然后要复制内容,然后再粘贴内容,然后回车,那么代码如下:

from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get(‘http://www.bcbxhome.com’)

driver.maximize_window()
driver.find_element_by_id(“scbar_txt”).send_keys(“selenium”)
driver.find_element_by_id(“kw”).send_keys(Keys.CONTROL,‘a’)
time.sleep(2)
driver.find_element_by_id(“kw”).send_keys(Keys.CONTROL,‘v’)
time.sleep(2)
driver.find_element_by_id(“su”).send_keys(Keys.ENTER)
复制代码