【问题标题】:How to click on element through "data-ng-click" attribute using Selenium如何使用 Selenium 通过“data-ng-click”属性单击元素
【发布时间】:2020-09-24 19:33:17
【问题描述】:

如何使用 Selenium 向以下元素发送点击?

注意:它们放置在同一个页面,并且它们都具有相同的类“btn btn-primary”

<button class="btn btn-primary" data-ng-click="ctrl.findInstrumentsBySearch(ctrl.filterInstrument);" data-ng-disabled="ctrl.disableButtonSearchInstrument();">
    <span class="fa fa-search"></span> Pesquisar
</button>

<button class="btn btn-primary" data-ng-click="ctrl.downloadLimitInstrumentCsv(ctrl.filterInstrument,{ filename: &quot;export.csv&quot; });">
    <span class="fa fa-file-excel-o"></span> Exportar
</button>

当我尝试使用以下内容时,我收到错误“IndexError: list index out of range”:

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

browser = webdriver.Chrome()
browser.get(("https://line.bvmfnet.com.br/#/limits/1"))
python_button = browser.find_elements_by_xpath("//button[@class='btn btn-primary' and @data-ng-click='ctrl.findInstrumentsBySearch(ctrl.filterInstrument)']")[0]
python_button.click()

【问题讨论】:

  • 到目前为止你尝试了什么?
  • browser.find_element_by_css_selector(".btn-primary").click() browser.find_element_by_class_name('data-ng-click').click() 和其他一些变体......
  • 它们是否在任何类型的 iframe 中?
  • 试试css选择器.btn.btn-primary。
  • 将您当前的代码尝试连同结果一起添加到您的问题中。您是否已验证您的定位器是唯一标识您想要的元素?我的猜测是,您的定位器定位了多个元素,而第一个(它正在单击)不是您要单击的元素,因此似乎什么也没做,至少不是您想要的。

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

要点击文本为 save 的元素,您可以使用以下任一Locator Strategies

  • Pesquisar

    • 使用css_selector

      driver.find_element_by_css_selector("button.btn.btn-primary[data-ng-click*='findInstrumentsBySearch'][data-ng-disabled*='disableButtonSearchInstrument']").click()
      
    • 使用xpath

      driver.find_element_by_xpath("//button[@class='btn btn-primary' and contains(@data-ng-click, 'findInstrumentsBySearch')][contains(., 'Pesquisar')]").click()
      

理想情况下,点击您需要为WebDriverWait 诱导element_to_be_clickable() 的元素,您可以使用以下任一Locator Strategies

  • 导出器

    • 使用CSS_SELECTOR

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-primary[data-ng-click*='downloadLimitInstrumentCsv']"))).click()
      
    • 使用XPATH

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary' and contains(@data-ng-click, 'downloadLimitInstrumentCsv')][contains(., 'Exportar')]"))).click()
      
  • 注意:您必须添加以下导入:

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

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    相关资源
    最近更新 更多