Selenium基礎知識(二)鼠標操作


一、鼠標操作

這個需要使用webdriver下的ActionChains類,這個類是操作鼠標操作的:

from selenium.webdriver import ActionChains

鼠標操作可分為三類:鼠標移動、鼠標拖拽、鼠標點擊

element = driver.find_element_by_name('tj_settingicon')
#鼠標點擊
ActionChains(driver).click(element).perform() #單擊某元素
ActionChains(driver).click_and_hold(element).perform() #在此元素上按下左鍵不放
ActionChains(driver).context_click(element).perform() #在此元素上單擊右鍵
ActionChains(driver).double_click(element).perform() #在此元素上雙擊
#鼠標拖拽
ActionChains(driver).drag_and_drop(source,target).perform() #從一個元素的位置,拖至另一個元素位置松開
ActionChains(driver).drag_and_drop_by_offset(source,xoffset,yoffset) #以坐標的形式拖拽,x,y

#鼠標移動
ActionChains(driver).move_by_offset(x,y) #移動到(x,y)坐標位置
ActionChains(driver).move_to_element(element) #鼠標移動到某個元素上
ActionChains(driver).move_to_element_with_offset(element,x,y) #移動到某個元素上,然后,在移動到相對坐標(x,y)上

上圖所示,會看到,每個方法后都跟了一個perform()很奇怪是不是,這個perform相當於submit提交。

如果你的方法后邊不寫這個,舉個例子,百度一下,你就知道

ActionChains(driver).click(element)  沒有preform()

如果后邊沒有跟這個,你可以看到,鼠標是點擊了,但是沒有進行搜索,所以perform相當於提交

 

示例代碼:

百度搜索selenium,點擊百度一下;鼠標移動到,設置上,點擊動態顯示的列表,高級搜索

#*_*coding:utf-8*_*

from selenium import webdriver
from selenium.webdriver import ActionChainsimport time

driver = webdriver.Ie()
driver.get('https://www.baidu.com/')
#輸入selenium 搜索
driver.find_element_by_id('kw').send_keys('selenium')
driver.find_element_by_id('su').click()

#移動到 設置
element = driver.find_element_by_name('tj_settingicon')
ActionChains(driver).move_to_element(element).perform()

#單擊,彈出的Ajax
driver.find_element_by_link_text('高級搜索').click()



 


免責聲明!

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



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