一、鼠标
1、导包:
from selenium.webdriver.common.action_chains import ActionChains
2、常规操作
2.1 左键单击
search_ele = WebDriverWait(driver, 15, 0.5).until(EC.visibility_of_element_located(("id", "search-input")))
search_ele.send_keys("手机")
# 查找搜索按钮
search_button = WebDriverWait(driver, 15, 0.5).until(EC.visibility_of_element_located(("id", "ai-topsearch")))
action = ActionChains(driver)
# 左键点击
action.click(search_button)
action.perform()
2.2 右键点击
login_ele = WebDriverWait(driver, 15, 0.5).until(EC.visibility_of_element_located(("link text", "登录")))
action = ActionChains(driver)
# 鼠标右键
action.context_click(login_ele)
action.perform()
2.3 左键双击
welcome_text = WebDriverWait(driver, 15, 0.5).until(EC.presence_of_element_located(("xpath", "/html/body/div[6]/div/div[1]/div[1]/em/span/em[1]")))
action = ActionChains(driver)
# 鼠标左键双击
action.double_click(welcome_text)
action.perform()
2.4 鼠标左键单击,不松开;拖动到某个元素上后,松开
login_ele = WebDriverWait(driver, 15, 0.5).until(EC.visibility_of_element_located(("link text", "登录")))
search_ele = WebDriverWait(driver, 15, 0.5).until(EC.visibility_of_element_located(("id", "search-input")))
action = ActionChains(driver)
action.drag_and_drop(login_ele, search_ele) # 有问题,系统鼠标干扰鼠标操作;在GUI操作系统上不能使用;
action.perform()
time.sleep(3)
print(search_ele.location) # 元素的位置信息的获取
print(search_ele.size) # 元素的尺寸的获取
action.drag_and_drop_by_offset(login_ele, search_ele.location["x"] + search_ele.size["width"]/2,search_ele.location["y"] + search_ele.size["height"]/2) # 有问题,系统鼠标干扰鼠标操作;在GUI操作系统上不能使用;
2.5 鼠标悬停在某个元素上
goods_type_element = WebDriverWait(driver, 15, 0.5).until(EC.visibility_of_element_located(("css selector", ".bd-name")))
action = ActionChains(driver)
action.move_to_element(goods_type_element)
action.perform()
# 当某个元素无法点击时,可先进行鼠标悬停操作,后点击
goods_type_element.click()
二、键盘
1、导包
from selenium.webdriver.common.keys import Keys
2、代码
Keys()类提供了键盘上几乎所有的按键方法,send_keys()不见可以模拟键盘输入,还可以用来输入键盘上的按键,甚至是组合键,例子如下:
# 模拟键盘事件
from selenium import webdriver
# 引入keys模块
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
# 输入框输入内容
driver.find_element_by_id("kw").send_keys("selenium")
# 输入“教程”
driver.find_element_by_id("kw").send_keys("教程")
# 删除“教程”
driver.find_element_by_id("kw").send_keys(Keys.BACK_SPACE)
...
3、常用操作
# 常用的键盘操作
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')
send_keys(Keys.CONTROL,'c')
send_keys(Keys.CONTROL,'v')
send_keys(Keys.CONTROL,'x')
send_keys(Keys.F1)
...
send_keys(Keys.F12)