簡體   English   中英

Selenium Python 點擊沒有 ID 的按鈕

[英]Selenium Python click a Button without ID

我有一個按鈕:

<button type="button" class="Buttonstyled__StyledButton-sc-140xkaw-1 bbPePk css-1n4k82t">Zum Warenkorb</button>

我想點擊這個按鈕,但我沒有 ID 還有其他方法嗎?

我正在學習 Selenium 也許有人能回答我這個問題會很好。 謝謝你!

您可以使用 class 名稱單擊,如下所示:

  1. Select

     button = driver.find_element_by_class_name('Buttonstyled__StyledButton-sc-140xkaw-1 bbPePk css-1n4k82t')
  2. 執行:

button.click()

在此示例中,“驅動程序”是 selenium 使用 Firefox Web 驅動程序的實例

Selenium 文檔可能會有所幫助: https://selenium-python.readthedocs.io/locating-elements.html

您實際上可以查找按鈕 class 來找到它(但它會返回包含該 class 的所有元素的列表,因為類不是唯一的):

driver.find_elements_by_css_selector('.theClass')

可以在此處找到詳細信息https://www.geeksforgeeks.org/find_elements_by_css_selector-driver-method-selenium-python/ ,但假設它是您可以使用的頁面中的第一個:

driver.find_elements_by_css_selector('.theClass')[0]

在您的情況下,它將是:

driver.find_elements_by_css_selector(".Buttonstyled__StyledButton-sc-140xkaw-1")[0]

假設它是頁面中的第一個。 如果它不是第一個帶有 class 的,那么您將必須選擇該方法返回的列表中的哪個是正確的。

Selenium 不僅可以根據元素的 id 值來定位元素。
定位符可以基於任何唯一的標簽名稱、任何元素屬性以及與某些其他元素的任何關系。
在這種特殊情況下,您的元素看起來包含獨特的文本。
如果是這樣,您可以根據該文本通過 XPath 找到它,如下所示:

driver.find_elements_by_xpath('//button[text()="Zum Warenkorb"]').click()

您還應該在訪問此元素之前添加一些等待/延遲,以便在您單擊它之前讓該元素完全加載。

您可以像這樣構造一個健壯的xpath

//button[contains(@class,'Buttonstyled__StyledButton') and text()='Zum Warenkorb']

然后像這樣使用它:

driver.find_element_by_xpath("//button[contains(@class,'Buttonstyled__StyledButton') and text()='Zum Warenkorb']").click()

或者如果它需要顯式等待則:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 50)
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class,'Buttonstyled__StyledButton') and text()='Zum Warenkorb']"))).click()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM