[英]Click button by text using Python and 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>
元素,您可以使用以下任一定位器策略:
使用xpath和text()
:
driver.find_element_by_xpath("//button[text()='button_text']").click()
使用xpath和contains()
:
driver.find_element_by_xpath("//button[contains(., 'button_text')]").click()
理想情況下,要通過文本定位並單擊<button>
元素,您需要為element_to_be_clickable()
引入WebDriverWait ,您可以使用以下任一定位器策略:
使用XPATH和text()
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='button_text']"))).click()
使用XPATH和contains()
:
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>
元素,您可以使用以下任一定位器策略:
使用xpath和text()
:
for button in driver.find_elements_by_xpath("//button[text()='button_text']"): button.click()
使用xpath和contains()
:
for button in driver.find_elements_by_xpath("//button[contains(., 'button_text')]"): button.click()
理想情況下,要通過文本定位所有<button>
元素,您需要為visibility_of_all_elements_located()
引入WebDriverWait ,您可以使用以下任一定位器策略:
使用XPATH和text()
:
for button in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//button[text()='button_text']"))): button.click()
使用XPATH和contains()
:
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.