我正在嘗試在 selenium 上使用 contains 功能,并嘗試在該特定文本存在時執行某個操作并單擊它。
如何使用 contains 函式driver.find.element()。到目前為止,我嘗試過:
if driver.find_element(By.LINK_TEXT, contains("Hello World")) == True:
driver.find_element(By.LINK_TEXT, "Hello World").click()
以及它的一些變體。
元素:
<a href="/xyz" target="_blank" class="btn btn-primary inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">"Hello World"</a>
uj5u.com熱心網友回復:
您可以使用包含():
driver.find_element(By.XPATH,".//*[contains(.,'Hello World')]")
或者
driver.find_element(By.XPATH,".//*[contains(text(),'Hello World')]")
或者
driver.find_element(By.XPATH,".//*[contains(@id,'Hello World')]")
句法:
//tagName[contains(@attribute_name,'attribute_value')]
或者
//*[contains(@attribute_name,'attribute_value')]
或者
//*[contains(text(),'value')]
uj5u.com熱心網友回復:
有一個By.PARTIAL_LINK_TEXT選擇器選項可以做鏈接文本的子字串。
uj5u.com熱心網友回復:
首先你應該使用driver.find_elements方法,不是driver.find_element因為沒有找到這樣的元素driver.find_element就會拋出例外,它不會回傳一個布林值 False。
Whiledriver.find_elements將回傳匹配的 Web 元素串列。如果找到匹配項,它將回傳一個非空串列,Python 會將其解釋為 Boolean True。否則,如果沒有找到匹配項,它將回傳一個空字串,Python 會將其解釋為 Boolean False。
如 AbiSaran 所述,您可以使用driver.find_element(By.XPATH,,如果字串包含',您可以使用如下斜杠“
if driver.find_elements(By.XPATH, "//a[contains(.,'fellow\'s world')]"):
driver.find_element(By.XPATH, "//a[contains(.,'fellow\'s world')]").click()
或者
elements = driver.find_elements(By.XPATH, "//a[contains(.,'fellow\'s world')]")
if elements:
elements[0].click()
uj5u.com熱心網友回復:
發現contains()我只是使用了而不是使用函式
def xyz():
try:
driver.find_element(By.CSS_SELECTOR, "button[class='h-10']")
except NoSuchElementException:
return False
return True
檢查該特定類、按鈕等是否存在并創建 while、if 函式來做出決定。
例如:
i = 0
while i<10:
xyz()
if xyz() == True:
driver.get("https://www.google.com/")
else:
abc()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/512219.html
