导入 from selenium.webdriver.common.keys import Keys
格式:Keys.XXX
一般这么用:send_keys(Keys.XXX)
# Keys.BACK_SPACE:回退键(BackSpace)
# Keys.TAB:制表键(Tab)
# Keys.ENTER:回车键(Enter)
# Keys.SHIFT:大小写转换键(Shift)
# Keys.CONTROL:Control键(Ctrl)
# Keys.ALT:ALT键(Alt)
# Keys.ESCAPE:返回键(Esc)
# Keys.SPACE:空格键(Space)
# Keys.PAGE_UP:翻页键上(Page Up)
# Keys.PAGE_DOWN:翻页键下(Page Down)
# Keys.END:行尾键(End)
# Keys.HOME:行首键(Home)
# Keys.LEFT:方向键左(Left)
# Keys.UP:方向键上(Up)
# Keys.RIGHT:方向键右(Right)
# Keys.DOWN:方向键下(Down)
# Keys.INSERT:插入键(Insert)
# DELETE:删除键(Delete)
# NUMPAD0 ~ NUMPAD9:数字键1-9
# F1 ~ F12:F1 - F12键
# (Keys.CONTROL, ‘a’):组合键Control+a,全选
# (Keys.CONTROL, ‘c’):组合键Control+c,复制
# (Keys.CONTROL, ‘x’):组合键Control+x,剪切
# (Keys.CONTROL, ‘v’):组合键Control+v,粘贴
1 # coding=UTF-8 2 #18.模拟键盘单个按键操作 3 import sys 4 reload(sys) 5 sys.setdefaultencoding('utf8') 6 from selenium import webdriver 7 import unittest 8 import time 9 from selenium.webdriver.common.keys import Keys 10 11 class Case18(unittest.TestCase): 12 13 def setUp(self): 14 self.driver = webdriver.Chrome() 15 16 def test_simulateASingleKey(self): 17 url = "https://www.sogou.com" 18 self.driver.get(url) 19 element = self.driver.find_element_by_id("query") 20 element.send_keys(Keys.F12) # 按下F12键 21 time.sleep(2) 22 element.send_keys(Keys.F12) 23 element.send_keys("selenium") 24 element.send_keys(Keys.CONTROL,'a') #c trl+a 全选输入框内容 25 time.sleep(2) 26 element.send_keys(Keys.CONTROL,'x') # ctrl+x 剪切输入框内容 27 time.sleep(2) 28 element.send_keys(Keys.CONTROL,'v') # ctrl+v 粘贴内容到输入框 29 time.sleep(2) 30 element.send_keys(Keys.ENTER) # 回车 31 time.sleep(2) 32 33 def tearDown(self): 34 self.driver.quit() 35 36 if __name__ == '__main__': 37 unittest.main()