簡體   English   中英

使用 Python 和 Selenium 按文本單擊按鈕

[英]Click button by text using Python and Selenium

是否可以使用Selenium單擊具有相同文本的多個按鈕?

文本 = 在此處解鎖此結果

您可以通過文本查找所有按鈕,然后在for循環中為每個按鈕執行click()方法。

使用這個 SO 答案,它會是這樣的:

buttons = driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")

for btn in buttons:
    btn.click()

我還建議您查看Splinter ,它是 Selenium 的一個很好的包裝器。

Splinter 是現有瀏覽器自動化工具(例如 Selenium、PhantomJS 和 zope.testbrowser)之上的抽象層。 它具有高級 API,可以輕松編寫 Web 應用程序的自動化測試。

我在 html 中有以下內容:

driver.find_element_by_xpath('//button[contains(text(), "HELLO")]').click()

@nobodyskiddy,嘗試使用driver.find_element (如果您有單個按鈕選項),當您使用driver.find_elements時使用index to click()find_elements會將數組返回到web 元素值,因此您必須使用index選擇或單擊。

要通過文本定位並單擊<button>元素,您可以使用以下任一定位器策略

  • 使用xpathtext()

     driver.find_element_by_xpath("//button[text()='button_text']").click()
  • 使用xpathcontains()

     driver.find_element_by_xpath("//button[contains(., 'button_text')]").click()

理想情況下,要通過文本定位並單擊<button>元素,您需要為element_to_be_clickable()引入WebDriverWait ,您可以使用以下任一定位器策略

  • 使用XPATHtext()

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='button_text']"))).click()
  • 使用XPATHcontains()

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'button_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

更新

要通過文本定位所有<button>元素,您可以使用以下任一定位器策略

  • 使用xpathtext()

     for button in driver.find_elements_by_xpath("//button[text()='button_text']"): button.click()
  • 使用xpathcontains()

     for button in driver.find_elements_by_xpath("//button[contains(., 'button_text')]"): button.click()

理想情況下,要通過文本定位所有<button>元素,您需要為visibility_of_all_elements_located()引入WebDriverWait ,您可以使用以下任一定位器策略

  • 使用XPATHtext()

     for button in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//button[text()='button_text']"))): button.click()
  • 使用XPATHcontains()

     for button in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//button[contains(., 'button_text')]"))): button.click()
  • 注意:您必須添加以下導入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

暫無
暫無

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

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