selenium--鼠标操作
前戏
在我们做自动化的时候,有时候会用到鼠标的一些操作,比如双击,鼠标悬浮等操作,selenium提供了ActionChains方法来供我们操作
双击
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from time import sleep driver = webdriver.Chrome() driver.get('http://www.baidu.com') driver.maximize_window() driver.find_element_by_css_selector('#kw').send_keys('python') sleep(2) # 将定位到的搜索框赋给变量 choose = driver.find_element_by_css_selector('#kw') # 鼠标双击 ActionChains(driver).double_click(choose).perform() sleep(2) driver.quit()
鼠标右键
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from time import sleep driver = webdriver.Chrome() driver.get('http://www.baidu.com') driver.maximize_window() driver.find_element_by_css_selector('#kw').send_keys('python') sleep(2) # 将定位到的搜索框赋给变量 choose = driver.find_element_by_css_selector('#kw') # 鼠标双击 ActionChains(driver).double_click(choose).perform() sleep(2) # 鼠标右键 ActionChains(driver).context_click(choose).perform() sleep(2) driver.quit()
鼠标悬浮
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from time import sleep driver = webdriver.Chrome() driver.get('http://www.baidu.com') driver.maximize_window() driver.find_element_by_css_selector('#kw').send_keys('python') sleep(2) # 定位到 class=pf,赋给变量 move move = driver.find_element_by_css_selector('.pf') # 鼠标悬浮 ActionChains(driver).move_to_element(move).perform() sleep(2) driver.quit()