我一直在嘗試單擊下面 html 代碼中的第二個按鈕而不使用
find_element_by_xpath
我想嘗試按類名定位元素,但我不斷收到錯誤訊息。
網址:
<div class="amount-control"
<button class="btn btn-primary btn-fab" type="button"
<span class="mdi mdi-minus" aria-hidden="true"></span>
<span class="sr-only">-</span>
</button>
<button class="btn btn-primary btn-fab" type="button"
<span class="mdi mdi-plus" aria-hidden="true"></span>
<span class="sr-only"> </span>
</button>
我的代碼:
button = driver.find_elements(By.XPATH, "//button[contains(@class, 'btn-primary')]//*[(@class, 'mdi-plus')]/..").click()
有人知道如何在不使用 xpath 或完整 xpath 的情況下找到按鈕并單擊它嗎?
uj5u.com熱心網友回復:
您可以簡單地使用 css 選擇器來查找您想要的元素。這里有兩個帶有 class 的 div 按鈕amount-control。如果您想找到該 div 下的第一個按鈕,可以將find_element_by_css_selector與以下 css 選擇器一起使用:
button = driver.find_element_by_css_selector('div.amount-control > button:first-child')
如果您想獲得第二個按鈕,只需更改:first-child,以:nth-of-type(2)這樣的:
button = driver.find_element_by_css_selector('div.amount-control > button:nth-of-type(2)')
uj5u.com熱心網友回復:
要單擊文本為 的元素,您可以使用以下任一定位器策略:
使用css_selector:
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-primary.btn-fab > span.mdi-plus span.sr-only").click()使用xpath:
driver.find_element(By.XPATH, "//button[@class='btn btn-primary btn-fab']//span[@class='sr-only' and text()=' ']").click()
理想情況下,要單擊可點擊元素,您需要為element_to_be_clickable()引入WebDriverWait,您可以使用以下任一定位器策略:
使用CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-primary.btn-fab > span.mdi-plus span.sr-only"))).click()使用
XPATH:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary btn-fab']//span[@class='sr-only' and text()=' ']"))).click()注意:您必須添加以下匯入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
uj5u.com熱心網友回復:
//button[@class="btn btn-primary btn-fab"][.//span[@class="mdi mdi-plus"]]
還應該是一個有效的 xpath,其中包含具有該類的跨度以定位按鈕。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/385898.html
標籤:Python 硒 路径 css-选择器 网络驱动程序等待
