[英]How to click the second element if the first element is not clickable using Python Selenium
[英]How to click an element that contains visible text and is clickable with selenium with python
根據其包含的文本(其他)要單擊的元素:
<a class="blah" href="/some_page/"><span>15</span> others</a>
失敗的項目:
driver.find_element(By.XPATH, "//*[contains(text(), ' others')]").click()
錯誤:
NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[contains(text(), 'others')]"}
要定位可點擊元素,您需要為element_to_be_clickable()誘導WebDriverWait ,您可以使用以下任一定位器策略:
使用CSS_SELECTOR :
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.blah[href='/some_page/'] > span"))).click()
使用XPATH :
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='blah' and @href='/some_page/'][contains(., 'others')]"))).click()
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在以下位置找到一些關於NoSuchElementException的相關討論:
DebanjanB 的答案的另一種替代方法是使用受 XPath contains(text(),'some string') 啟發的不同 xpath contains(text(),'some string') 與具有多個文本子節點的節點一起使用時不起作用
"//*[text()[contains(.,' others')]]"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.