[英]How to click an element using Selenium Python
所以我在 HTML 中有這個元素......
<a href="#" onclick="on_catolog(2);"><span style="font-size:11pt">Security</span></a>
... 我想在 python 中使用 Selenium 單擊它。我該怎么做? (也許我可以使用 onclick 來識別它,但是如何呢?)
另外,這是我嘗試過的:
security = driver.find_element_by_xpath("//button[@onclick=\"on_catolog(2);\"]")
security.click()
您在 XPath "//button[@onclick=\"on_catolog(2);\"]"
中使用了錯誤的標簽名稱。 它不是按鈕,而是錨標記。 嘗試
"//a[@onclick='on_catolog(2);']"
或點擊鏈接文字:
security = driver.find_element_by_link_text("Security")
security.click()
要單擊帶有文本作為安全性的元素,您可以使用以下任一定位器策略:
使用css_selector
:
driver.find_element_by_css_selector("a[onclick^='on_catolog'] > span[style='font-size:11pt']").click()
使用xpath
:
driver.find_element_by_xpath("//a[starts-with(@onclick, 'on_catolog')]/span[text()='Security']").click()
理想情況下,要單擊您需要為element_to_be_clickable()
引入WebDriverWait的元素,您可以使用以下任一定位器策略:
使用CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[onclick^='on_catolog'] > span[style='font-size:11pt']"))).click()
使用XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@onclick, 'on_catolog')]/span[text()='Security']"))).click()
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.