selenium基本使用之滑鼠操作
使用ActionChains類中提供的方法實作滑鼠點擊,拖拽等相關的操作,使用如下:
#driver即瀏覽器驅動,element被操作的元素物件,perform對整個操作進行提交
#滑鼠左擊(單擊)
ActionChains(driver).click(element).perform()
#滑鼠右擊
ActionChains(driver).context_click(element).perform()
#滑鼠雙擊
ActionChains(driver).double_click(element).perform()
#滑鼠移動
ActionChains(driver).click_and_hold(element).perform()
#滑鼠拖拽,source--源元素,target--目標元素
ActionChains(driver).drag_and_drop(source,target).perform()
下面以該http://sahitest.com/demo/網頁為例,測驗相關操作:
#匯入相應的包
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
driver = webdriver.Chrome()
#獲取網頁
driver.get("http://sahitest.com/demo/")
# 進入滑鼠點擊操作測驗頁面
driver.find_element_by_xpath('/html/body/table/tbody/tr/td[5]/a[1]').click()
sleep(5)
# 左擊
left_click = driver.find_element_by_xpath('/html/body/form/input[3]')
ActionChains(driver).click(left_click).perform()
sleep(5)
# 右擊
right_click = driver.find_element_by_xpath('/html/body/form/input[4]')
ActionChains(driver).context_click(right_click).perform()
sleep(5)
# 雙擊
db_click = driver.find_element_by_xpath('/html/body/form/input[2]')
ActionChains(driver).double_click(db_click).perform()
sleep(5)
# 回傳主頁面
driver.back()
sleep(5)
# 找到滑鼠移動懸停測驗頁面
driver.find_element_by_xpath('/html/body/table/tbody/tr/td[5]/a[3]').click()
sleep(3)
# 滑鼠懸停
hold_click = driver.find_element_by_xpath('/html/body/a[1]/span')
ActionChains(driver).click_and_hold(hold_click).perform()
sleep(3)
# 滑鼠移動
move_click1 = driver.find_element_by_xpath('/html/body/form/input[1]')
ActionChains(driver).move_to_element(move_click1).perform()
sleep(3)
move_click2 = driver.find_element_by_xpath('/html/body/form/input[2]')
ActionChains(driver).move_to_element(move_click2).perform()
sleep(3)
# 回傳主頁面
driver.back()
sleep(5)
# 找到拖拽測驗頁面
driver.find_element_by_xpath('/html/body/table/tbody/tr/td[5]/a[5]').click()
sleep(3)
# 滑鼠拖拽
# 源元素
source = driver.find_element_by_xpath('//*[@id="dragger"]')
# 目標元素
target = driver.find_element_by_xpath('/html/body/div[2]')
ActionChains(driver).drag_and_drop(source,target).perform()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/274732.html
標籤:python
