【问题标题】:Selenium chromedriver cannot click href linkSelenium chromedriver 无法点击 href 链接
【发布时间】:2021-02-19 18:43:31
【问题描述】:

我正在编写一个脚本来自动收集数据,但在单击链接时遇到了问题。该网站在登录后,但我成功导航。我在尝试导航到下载页面时遇到了问题。这是在 python 中使用 chrome webdriver。

我尝试过使用:

find_element_by_partial_link_text('stuff').click()
find_element_by_xpath('stuff').click()
#and a few others

当我尝试一些选择器语句时,我得到以下消息的迭代。

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"download"}
  (Session info: chrome=88.0.4324.182)

我尝试使用的 HTML 源是:

<a routerlink="/download" title="Download" href="/itron-mvweb/download"><i class="fa fa-lg fa-fw fa-download"></i><span class="menu-item-parent">Download</span></a>

谢谢!

【问题讨论】:

  • 什么样的问题?请参阅How to Ask
  • @Seth 是的,对不起。现已更新。
  • 似乎是由拼写错误引起的。 Download 需要大写(由于区分大小写)。

标签: python selenium-webdriver xpath css-selectors webdriverwait


【解决方案1】:

这是由拼写错误引起的。 Download 区分大小写,请务必将D 大写!

【讨论】:

    【解决方案2】:

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

    • 使用css_selector

      driver.find_element(By.CSS_SELECTOR, "a[title='Download'][href='/itron-mvweb/download'] span.menu-item-parent").click()
      
    • 使用xpath

      driver.find_element(By.XPATH, "//a[@title='Download' and @href='/itron-mvweb/download']//span[@class='menu-item-parent' and text()='Download']").click()
      

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

    • 使用CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[title='Download'][href='/itron-mvweb/download'] span.menu-item-parent"))).click()
      
    • 使用XPATH:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@title='Download' and @href='/itron-mvweb/download']//span[@class='menu-item-parent' and text()='Download']"))).click()
      
    • 注意:您必须添加以下导入:

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

    参考文献

    您可以在NoSuchElementException 上找到一些相关讨论:

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多