selenium - webdriver keys 键盘操作
webdriver的Keys()类,提供了几乎所有按键的方法,常用的如下:
- Keys.BACK_SPACE 删除键
- Keys.SPACE 空格键
- Keys.TAB 制表键(Tab)
- Keys.ESCAPE 回退键(Esc)
- Keys.ENTER 回车键(Enter)
- Keys.CONTROL Ctrl键
ps:元素的send_keys()方法,可以模拟键盘输入
常用的键盘操作示例:
最终输入结果为:zhangyan ffzhangyan ff
from selenium import webdriver from selenium.webdriver.common.keys import Keys # 导入Keys类 import time driver = webdriver.Chrome() driver.get('http://www.baidu.com') driver.find_element_by_id('kw').send_keys('zhangyang') time.sleep(2) driver.find_element_by_id('kw').send_keys(Keys.BACK_SPACE) time.sleep(2) driver.find_element_by_id('kw').send_keys(Keys.SPACE) time.sleep(2) driver.find_element_by_id('kw').send_keys('ff') time.sleep(2) driver.find_element_by_id('kw').send_keys(Keys.CONTROL, 'a') # ctrl+a 全选输入框内容 time.sleep(2) driver.find_element_by_id('kw').send_keys(Keys.CONTROL, 'c') # ctrl+c 复制输入框内容 time.sleep(2) driver.find_element_by_id('kw').click() driver.find_element_by_id('kw').send_keys(Keys.CONTROL, 'v') # ctrl+a 粘贴输入框内容 time.sleep(2) driver.find_element_by_id('su').send_keys(Keys.ENTER) # 通过回车键来代替单击操作 time.sleep(5) driver.close()
在使用pageObject模式时,对page对象使用键盘操作时,如果有两个按键操作,需要使用+连接,而不是逗号连接
例如:
ele.send_keys(Keys.CONTROL + 'a')
mac上操作键盘有些不同:
1. 安装第三方包 pip install PyUserInput
2. 代码如下:
from pykeyboard import PyKeyboard k=PyKeyboard() k.press_keys(['Command', 'a'])
k.press_keys(['Delete'])