Web自动化测试:模拟键盘事件(Keys)

邮差的信 提交于 2020-08-10 09:36:53

如何使用引入的common.keys库来模拟键盘来操控浏览器

一、基础写法
具体用法其实和我们之前对浏览器输入框所用的方法:send_keys()是一样的,只不过我们通过keys类,可以输入webdriver包中对应的键盘操作。

首先导入keys库

from selenium.webdriver.common.keys import Keys

输入单个键盘按键:

小键盘按键3:send_keys(Keys.NUMPAD3)

输入多次的同一个按键

按10次小键盘按键3:send_keys(Keys.NUMPAD3*10)

输入组合按键:

全选Ctrl+A: send_keys(Keys.CONTROL, "a")

二、键盘按键引用对照
我们通过keys类中,找到了键盘按键所对应的值:

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'
实例详解:
百度注册页面,我们把手机号码输入框中的数据,通过键盘按键Ctrl + C 、Ctrl + V复制到用户名输入框

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

from time import sleep

# 模拟键盘操作-百度登录页面

driver = webdriver.Chrome()

driver.get("https://passport.baidu.com/v2/?reg")

# 用户名元素定位和手机号元素定位

name_element=driver.find_element_by_css_selector("#TANGRAM__PSP_3__userName")

phone_element=driver.find_element_by_css_selector("#TANGRAM__PSP_3__phone")

# 在名字输入框输入10个数字键3

name_element.send_keys(Keys.NUMPAD3*10)

# 在手机号输入框输入手机号码

phone_element.send_keys("18812345678")

# 在手机号输入框进行组合键Ctrl+a 、 Ctrl+x

phone_element.send_keys(Keys.CONTROL, "a")

sleep(1)

phone_element.send_keys(Keys.CONTROL, "x")

# 在名字输入框输入组合键Ctrl+v

name_element.clear()

name_element.send_keys(Keys.CONTROL, "v")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!