Selenium chromedriver 无法点击 href 链接

时间:2021-02-19 18:43:31

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

我正在编写一个脚本来自动收集数据,但在单击链接时遇到问题。该网站在登录后,但我成功导航。我在尝试导航到下载页面时遇到了问题。这是在 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>

谢谢!

2 个答案:

答案 0 :(得分:2)

这是由打字错误引起的。 Download 区分大小写,请确保将 D 大写!

答案 1 :(得分:0)

要点击带有下载文本的元素,您可以使用以下任一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 的相关讨论: