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

10 python selenium python-2.7 python-3.x

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

Text =在此处解锁此结果

kch*_*ski 14

您可以按文本查找所有按钮,然后click()for循环中为每个按钮执行方法.

使用这个SO 答案,它将是这样的:

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

for btn in buttons:
    btn.click()
Run Code Online (Sandbox Code Playgroud)

我还建议你看看Splinter,它是Selenium的一个很好的包装器.

Splinter是现有浏览器自动化工具(如Selenium,PhantomJS和zope.testbrowser)之上的抽象层.它有一个高级API,可以轻松编写Web应用程序的自动化测试.

  • 在我给出的示例中,您不是在寻找给定的*绝对* xpath,而是在寻找按钮包含的文本。 (2认同)

Deb*_*anB 10

<button>要通过文本定位并单击元素,您可以使用以下定位器策略之一:


<button>理想情况下,要通过文本定位并单击元素,您需要引发WebDriverWait ,并且element_to_be_clickable()可以使用以下定位器策略之一:

  • 使用XPATHtext()

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

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'button_text')]"))).click()
    
    Run Code Online (Sandbox Code Playgroud)
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    Run Code Online (Sandbox Code Playgroud)

更新

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


<button>理想情况下,要通过文本定位所有元素,您需要引发WebDriverWait ,并且visibility_of_all_elements_located()可以使用以下定位器策略之一:

  • 使用XPATHtext()

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

    for button in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//button[contains(., 'button_text')]"))):
      button.click()
    
    Run Code Online (Sandbox Code Playgroud)
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    Run Code Online (Sandbox Code Playgroud)


Nis*_*eth 7

我在 html 中有以下内容:

driver.find_element_by_xpath('//button[contains(text(), "HELLO")]').click()
Run Code Online (Sandbox Code Playgroud)