一、定位到元素后,常用的元素操作方法:
clear():清除文本,比如输入用户名、密码之前先清除输入框中的内容
send_keys(*value):输入内容
click():单击元素
submit():提交的必须是表单元素
size:返回元素的尺寸
text:获取元素的文本
get_attribute(name):获得属性值
is_displayed():返回元素是否用户可见
二、鼠标操作事件
webdriver将鼠标相关的操作封装在ActionChains类中,使用前需要先引入:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains封装了如下图所示的操作鼠标的方法:
perform():执行ActionChains中的行为,相当于是对相关动作的提交
context_click():鼠标右键
#定位到要右击的元素
qqq =driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/div/div[3]/table/tbody/tr/td[2]")
#对定位到的元素执行鼠标右键操作
ActionChains(driver).context_click(qqq).perform()
double_click():鼠标双击
#定位到要双击的元素
qqq =driver.find_element_by_xpath("xxx")
#对定位到的元素执行鼠标双击操作
ActionChains(driver).double_click(qqq).perform()
drag_and_drop(source,target):鼠标拖动
#定位元素的原位置
element = driver.find_element_by_name("source")
#定位元素要移动到的目标位置
target = driver.find_element_by_name("target")
#执行元素的移动操作
ActionChains(driver).drag_and_drop(element, target).perform()
drag_and_drop_by_offset(source, xoffset, yoffset):拖动时指定偏移量
move_by_offset(xoffset, yoffset)
move_to_element(to_element):鼠标悬停操作
move_to_element_with_offset(to_element, xoffset, yoffset):移动到距某个元素(左上角坐标)多少距离的位置
三、键盘操作事件
键盘相关的操作封装到了Keys()类中,使用前需要先引入:
from selenium.webdriver.common.keys import Keys
Keys类中定义了键对应的code:
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'
常用键盘操作:
send_keys(Keys.BACK_SPACE) 删除键(BackSpace) send_keys(Keys.SPACE) 空格键(Space) send_keys(Keys.TAB) 制表键(Tab) send_keys(Keys.ESCAPE) 回退键(Esc) send_keys(Keys.ENTER) 回车键(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.F12) 键盘F12