selenium之ActionChains模擬用戶行為


1、需求:需要模擬鼠標操作才能進行的情況,比如單擊、雙擊、鼠標右鍵、拖拽等操作

2、解決辦法:selenium 提供了一個類來處理這類事件:selenium.webdriver.common.action_chains.ActionChains(driver)

3、腳本:from selenium.webdriver.common.action_chains import AchtionChains

4、原理:調用ActionChains不會立即執行,而是將所有的操作順序放在一個隊列里,當調用perform()方法時,隊列中的事件會被依次執行

5、寫法:支持鏈式寫法和分步寫法

ActionChains(driver).click(ele).perform()

6、鍵盤和鼠標方法列表:

(1)perform()執行列表中所有的操作

(2)click(on_element=None)  單擊鼠標左鍵

(3)context_click(on_element=None)  單擊鼠標右鍵

(4)double_click(on_element=None)  雙擊鼠標左鍵

(5)move_to_element(to_element)  移動鼠標到某個元素上

(6)ele.send_kends(keys_to_send)  發送某個詞到當前焦點的元素

7、不常用的方法列表:

(1)click_and_hold(on_element=None)  點擊鼠標左鍵不松開

(2)release(on_element=None)  在某個元素位置松開鼠標左鍵

(3)key_down(value,element=None)  按下鍵盤上的某個鍵

(4)key_up(value,element=None)  松開鍵盤上的某個鍵

(5)drag_and_drop(source,target)  拖拽到某個元素然后松開

(6)drag_and_drop_by_offset(source,xoffset,yoffset)  拖拽到某個坐標然后松開

(7)move_by_offset(xoffset,yoffset)  鼠標從當前位置移動到某個坐標

(8)move_to_element_with_offset(to_element,xoffset,yoffset)  移動到距某個元素(左上角坐標)多少距離的位置  

 

例子:

# coding utf-8
from selenium import webdriver
# 導入sleep這個模塊
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains

# 打開淘寶首頁
url = "https://www.taobao.com/"
driver = webdriver.Firefox()
driver.get(url)
# 睡眠時間3秒,看的效果明顯點
sleep(3)

# 通過find_element_by_css_selector定位到“女裝”
menu_element = driver.find_element_by_css_selector("li.J_Cat:nth-child(1) > a:nth-child(1)")
# 把鼠標移到女裝上
ActionChains(driver).move_to_element(menu_element).perform()

sleep(10)
#sreach_window=driver.current_window_handle
# 選擇女裝中的“羽絨棉服”
driver.find_element_by_xpath("/html/body/div[4]/div[1]/div[1]/div[1]/div/div/div[1]/div[1]/div[1]/p/a[3]").click()

注:一定要有睡眠時間,不然會由於資源沒有加載完導致定位不到我要定位的元素。這個問題困擾我很久


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM