python

当前位置:首页 > selenium教程 > 当前文章

selenium教程

selenium键盘按键Keys类及键盘码详解

2020-12-29 61赞 老董笔记
每篇文章努力于解决一个问题!更多精品可移步文章底部。

  selenium可以操作鼠标,此外它的Keys()类提供了操作键盘的途径,因为键盘上几乎所有按键都可以用Keys()类实现。 之前我们一直用元素的send_keys()方法输入文字,其实该方法也可以输入键盘的按键,按键就是Keys()类所提供。

  学习本文前你可以再回顾下提供键盘按键等交互行为的类ActionChains。其实在selenium之外还有基于python的键盘操作PyKeyboard模块,详情查看PyKeyboard按键操作

from selenium.webdriver.common.keys import Keys

  一些元素对象具备send_keys方法,比如获取一个元素element后,直接调用element.send_keys('xxxx')方法。

  看起来挺简单,其实还是有一些注意事项,比如页面回到顶部或者回到底部的操作最好定位body元素执行按键,经过实测定位到其他元素甚至输入框上也可以实现下拉,但理论上总是感觉不放心(说不定某种情况就报错了),所以最好注意下。下节课我们上代码看一下定位到不同元素页面下拉的效果!此外,send_keys有时候丢失字符,具体解决请查看selenium坑合集

  本节课是理论,下节课是实操。常见的按键如下

send_keys(Keys.SHIFT) shift键
send_keys(Keys.CONTROL) ctrl键
send_keys(Keys.ALT) alt键
send_keys(Keys.PAGE_UP) PaUp键
send_keys(Keys.PAGE_DOWN) PaDn键
send_keys(Keys.UP) 上
send_keys(Keys.DOWN) 下
send_keys(Keys.LEFT) 左
send_keys(Keys.RIGHT) 右
send_keys(Keys.COMMAND)
send_keys(Keys.BACK_SPACE) 删除键
send_keys(Keys.SPACE) 空格键
send_keys(Keys.TAB) 制表键
send_keys(Keys.ESCAPE) 回退键
send_keys(Keys.ENTER) 回车键
send_keys(Keys.CONTROL,'a') 全选(Ctrl+A)
send_keys(Keys.CONTROL,'c') 复制(Ctrl+C)
send_keys(Keys.CONTROL,'x') 剪切(Ctrl+X)
send_keys(Keys.CONTROL,'v') 粘贴(Ctrl+V)
send_keys(Keys.F1)  F1键
send_keys(Keys.F5)  F5键
……
send_keys(Keys.F12) F12键

  Set of special keys codes.

ADD = u'ue025'
ALT = u'ue00a'
ARROW_DOWN = u'ue015'
ARROW_LEFT = u'ue012'
ARROW_RIGHT = u'ue014'
ARROW_UP = u'ue013'
BACKSPACE = u'ue003'
BACK_SPACE = u'ue003'
CANCEL = u'ue001'
CLEAR = u'ue005'
COMMAND = u'ue03d'
CONTROL = u'ue009'
DECIMAL = u'ue028'
DELETE = u'ue017'
DIVIDE = u'ue029'
DOWN = u'ue015'
END = u'ue010'
ENTER = u'ue007'
EQUALS = u'ue019'
ESCAPE = u'ue00c'
F1 = u'ue031'
F10 = u'ue03a'
F11 = u'ue03b'
F12 = u'ue03c'
F2 = u'ue032'
F3 = u'ue033'
F4 = u'ue034'
F5 = u'ue035'
F6 = u'ue036'
F7 = u'ue037'
F8 = u'ue038'
F9 = u'ue039'
HELP = u'ue002'
HOME = u'ue011'
INSERT = u'ue016'
LEFT = u'ue012'
LEFT_ALT = u'ue00a'
LEFT_CONTROL = u'ue009'
LEFT_SHIFT = u'ue008'
META = u'ue03d'
MULTIPLY = u'ue024'
NULL = u'ue000'
NUMPAD0 = u'ue01a'
NUMPAD1 = u'ue01b'
NUMPAD2 = u'ue01c'
NUMPAD3 = u'ue01d'
NUMPAD4 = u'ue01e'
NUMPAD5 = u'ue01f'
NUMPAD6 = u'ue020'
NUMPAD7 = u'ue021'
NUMPAD8 = u'ue022'
NUMPAD9 = u'ue023'
PAGE_DOWN = u'ue00f'
PAGE_UP = u'ue00e'
PAUSE = u'ue00b'
RETURN = u'ue006'
RIGHT = u'ue014'
SEMICOLON = u'ue018'
SEPARATOR = u'ue026'
SHIFT = u'ue008'
SPACE = u'ue00d'
SUBTRACT = u'ue027'
TAB = u'ue004'
UP = u'ue013'

文章评论

selenium键盘按键Keys类及键盘码详解文章写得不错,值得赞赏