如何在Python的Selenium中使用Action Chain類的click()方法?
我們可以使用Selenium中Action Chain類的click()方法。這些類通常用於自動化互動,例如上下文選單點選、滑鼠按鈕操作、按鍵和滑鼠移動。
這些型別的操作主要在複雜的場景中很常見,例如拖放和將滑鼠懸停在頁面上的元素上。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物件後,我們可以像佇列一樣一個接一個地執行許多操作。
click() - 此方法對頁面上的元素執行點選操作。
語法
click(args)
其中args是要點選的元素。如果省略引數,它將點選滑鼠當前位置。
#element source = driver.find_element_by_id("name") #action chain object action = ActionChains(driver) # click operation action.click(source) # perform the action action.perform()
示例
點選元素的程式碼實現。
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/about/about_careers.htm") #to refresh the browser driver.refresh() # identifying the source element source= driver.find_element_by_xpath("//*[text()='Team']"); # action chain object creation action = ActionChains(driver) # click the element action.click(source) # perform the action action.perform() #to close the browser driver.close()
廣告