如何使用Python在Selenium中執行雙擊元素操作?
我們可以藉助Action Chains類在Selenium中執行元素的雙擊操作。這些類通常用於自動化諸如上下文選單點選、滑鼠按鈕操作、按鍵和滑鼠移動之類的互動。
這些型別的操作主要在複雜的場景中很常見,例如拖放和將滑鼠懸停在頁面上的元素上。Action Chains類的這些方法由高階指令碼使用。我們可以藉助Selenium中的Action Chains來操作DOM。
Action chain物件以佇列的形式實現ActionChains,然後執行perform()方法。呼叫perform()方法時,將執行action chains上的所有操作。
建立Action Chain物件的步驟如下:
首先,我們需要匯入Action Chain類,然後將驅動程式作為引數傳遞給它。
現在,所有action chains的操作都可以藉助此物件來完成。
語法
建立Action Chains物件的語法:
from selenium import webdriver
# import Action chains from selenium.webdriver import ActionChains # create webdriver object driver = webdriver.Firefox() # create action chain object action = ActionChains(driver)
建立Action Chains物件後,我們可以像一個排隊的鏈一樣,一個接一個地執行許多操作。
double_click() - 此方法對頁面上的元素執行雙擊操作。
語法
double_click(args)
其中args是要雙擊的元素。如果省略,則會對當前滑鼠位置進行點選。
#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# double click operation
action.double_click(source)示例
雙擊操作的程式碼實現。
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.tw/index.htm")
#to refresh the browser
driver.refresh()
# identifying the source element
source= driver.find_element_by_xpath("//*[text()='GATE Exams']");
# action chain object creation
action = ActionChains(driver)
# double click operation and perform
action.double_click(source).perform()
#to close the browser
driver.close()
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP