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

时间:2016-02-17 23:56:35

标签: python python-2.7 python-3.x selenium

是否可以点击带有Selenium相同文字的乘法按钮?

Text = Unlock this result here

4 个答案:

答案 0 :(得分:10)

您可以按文字找到所有按钮,然后对click()循环中的每个按钮执行for方法。

使用这个SO answer就可以这样:

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

答案 1 :(得分:2)

我在html中具有以下内容:

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

答案 2 :(得分:1)

要通过文本定位并单击 <button> 元素,您可以使用以下任一 Locator Strategies

  • 使用 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,您可以使用以下任一 Locator Strategies:< /p>

  • 使用 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> 元素,您可以使用以下任一 Locator Strategies

  • 使用 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,您可以使用以下任一 Locator Strategies

  • 使用 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
    

答案 3 :(得分:0)

@nobodyskiddy,尝试使用driver.find_element(如果您具有单个按钮选项),则在使用driver.find_elements时使用index来单击click(),find_elements将数组返回为webelement值,因此您必须使用index来选择或单击。