如何在 Python Selenium 中自動點選選單框/彈出右鍵單擊?


我們可以在 Python 中使用 ActionChains 類,用 Selenium 網頁驅動程式自動執行右鍵單擊操作。我們必須建立一個 ActionChains 類物件,然後對其應用相關的方法。

為了將滑鼠移動到要執行右鍵單擊的元素,我們將使用 move_to_element 方法並將元素定位器作為引數傳遞。

然後應用 context_click 方法執行右鍵單擊。最後,使用 perform 方法實際執行這些操作。此外,我們必須在程式碼中新增 from selenium.webdriver.common.action_chains import ActionChains 語句以使用 ActionChains 類。

語法

a = ActionChains(driver)
m= driver.find_element_by_id("hot-spot")
a.move_to_element(m)
a.context_click().perform

例項

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.alert import Alert
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://the-internet.herokuapp.com/context_menu")
#object of ActionChains
a = ActionChains(driver)
#identify element
m = driver.find_element_by_id("hot-spot")
#move mouse over element
a.move_to_element(m)
#perform right-click
a.context_click().perform()
#switch to alert
al = driver.switch_to.alert
#get alert text
s = al.text
print("Alert text: ")
print(s)
#accept alert
al.accept()
#close browser
driver.quit()

輸出

更新於: 06-4 月-2021

779 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告