使用Python和Selenium按文本单击按钮

问题描述 投票:0回答:5

是否可以使用Selenium单击具有相同文本的乘法按钮?

python selenium selenium-webdriver xpath webdriverwait
5个回答
31
投票

您可以通过文本找到所有按钮,然后在

click()
循环中为每个按钮执行
for
方法。

使用这个SOanswer,它会是这样的:

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 自动化测试 应用程序。


9
投票

要通过文本定位并单击

<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
    

8
投票

我在 html 中有以下内容:

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

1
投票

@nobodyskiddy,尝试使用

driver.find_element
(如果您有单个按钮选项),当您使用
click()
时,请使用
driver.find_elements
的索引,
find_elements
将返回数组到Web元素值,因此您必须使用要选择或单击的索引。


0
投票

CheckElementAttribute(driver.FindElement(By.Id("btnCopyBtn")), "启用", "true", "复制类型字段");

© www.soinside.com 2019 - 2024. All rights reserved.