我正在嘗試使用 selenium 選擇一個按鈕,但是我相信我在撰寫 xpath 時做錯了任何人都可以幫助我,我需要選擇貨幣歐元。鏈接:- 
我寫的定位器

USD = self.find_element_by_xpath(f"//a[contains(text(),'selected_currency='Euro']")
USD.click()
uj5u.com熱心網友回復:
下面的xpath
//a[contains(@href,'EUR') and starts-with(@class,'bui-list')]
在 HTML DOM 中出現兩次。
檢查步驟:
Press F12 in Chrome- >去element節- >做一個CTRL F- >再貼上xpath看看,如果你需要的element是越來越強調與1/1匹配的節點。
如果您想為您選擇 Suggest 中的第一個,則無需對 XPath 執行任何操作。
@pmadhu 的回答具有誤導性,因為在與 Selenium 一起使用時,為什么有人會在 XPath 中查找第一個索引?如果有多個匹配的節點,Selenium 總是會選擇第一個元素,所以我真的沒有任何意義為什么有人會使用[1]
盡管如此,
點擊為您推薦歐元:
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href,'EUR') and starts-with(@class,'bui-list')]"))).click()
except:
pass
進口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
如果您想點擊歐元的第二個匹配節點,
在這種情況下,使用索引 2 是有意義的。
XPath看起來像這樣:
(//a[contains(@href,'EUR') and starts-with(@class,'bui-list')])[2]
uj5u.com熱心網友回復:
您要查找的文本:selected_currency='EUR'在標簽的data-modal-header-async-url-param引數中a。你應該運行contains。
編輯:定位器: //a[contains(@data-modal-header-async-url-param, 'selected_currency=EUR')]
uj5u.com熱心網友回復:
正如已經解釋過的,selected_currency=EUR是在屬性 - 中data-modal-header-async-url-param。
但是,您可以使用以下代碼選擇所需的選項。
EUR選項的 xpath可以是 - //div[contains(text(),'EUR')]。由于它使用此 xpath- 突出顯示 DOM 中的 2 個元素(//div[contains(text(),'EUR')])[1]。找到唯一的定位器很重要。鏈接參考
# Imports required for Explicit wait
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.get("https://www.booking.com/")
wait = WebDriverWait(driver,30)
# Click on Choose currency option
wait.until(EC.element_to_be_clickable((By.XPATH,"//span[@class='bui-button__text']/span[contains(text(),'INR')]"))).click()
# Click on the EUR option.
euro_option = wait.until(EC.element_to_be_clickable((By.XPATH,"(//div[contains(text(),'EUR')])[1]")))
euro_option.click()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/350238.html
