Python爬蟲之Selenium滑鼠事件的實現
阿新 • • 發佈:2020-12-05
一、常用方法
函式名 | 說明 |
---|---|
click(on_element=None) | 點選滑鼠右鍵 |
click_and_hold(on_element=None) | 點選滑鼠左鍵,不鬆開 |
release(on_element=None) | 在某個元素位置鬆開滑鼠左鍵 |
context_click(on_element=None) | 點選滑鼠右鍵 |
double_click(on_element=None) | 雙擊滑鼠左鍵 |
drag_and_drop(source,target) | 拖拽到某個元素然後鬆開 |
drag_and_drop_by_offset(source,xoffset,yoffset) | 拽到某個座標然後鬆開 |
move_by_offset(xoffset,yoffset) | 滑鼠從當前位置移動到某個座標 |
move_to_element(to_element) | 滑鼠移動到某個元素 |
move_to_element_with_offset(to_element,yoffset) | 移動到距某個元素(左上角座標)多少距離的位置 |
perform() | 執行所有 ActionChains 中儲存的行為,相當於提交 |
二、程式碼示例
選幾個經常使用的測試一下,其他事件語法相同
from selenium import webdriver import time from selenium.webdriver import ActionChains driver = webdriver.Chrome() driver.get("https://www.baidu.cn") #定位到需要右擊的元素,然後執行滑鼠右擊操作(例:對新聞標籤進行右擊) context_click_location = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div/div[3]/a[1]') ActionChains(driver).context_click(context_click_location).perform() time.sleep(2) #睡兩秒,看一下效果 # 定位到需要懸停的元素,然後執行滑鼠懸停操作(例:對設定標籤進行懸停) move_to_element_location = driver.find_element_by_xpath("/html/body/div[1]/div[1]/div/div[3]/a[8]") ActionChains(driver).move_to_element(move_to_element_location).perform() time.sleep(2) #睡兩秒,看一下效果 # 滑鼠懸浮後點擊高階搜尋 driver.find_element_by_xpath("/html/body/div[1]/div[6]/a[2]").click() time.sleep(2) #睡兩秒,看一下效果 driver.quit() #關閉所有標籤頁
由於百度沒有可拖動的元素,所以在菜鳥上找了一個網址進行測試,由於菜鳥上的網頁是使用frame內嵌的,所以添加了個處理frame的過程,關於frame的處理請參考我的另一篇文章:Python爬蟲 - Selenium(8)frame/iframe表單巢狀頁面
from selenium import webdriver from selenium.webdriver import ActionChains import time driver = webdriver.Chrome() driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-example-draggable-scroll") # 切換到目標元素所在的frame driver.switch_to.frame("iframeResult") # 確定拖拽目標的起點和終點,完成拖拽 start_location = driver.find_element_by_id("draggable") end_location = driver.find_element_by_id("draggable3") ActionChains(driver).drag_and_drop(start_location,end_location).perform() time.sleep(2) #睡兩秒,看一下效果 driver.quit() #關閉所有標籤頁
到此這篇關於Python爬蟲之Selenium滑鼠事件的實現的文章就介紹到這了,更多相關Selenium 滑鼠事件內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!