【问题标题】:Can't click dynamic link using Python Selenium无法使用 Python Selenium 单击动态链接
【发布时间】:2021-05-21 21:22:45
【问题描述】:

我正在尝试使用 Selenium 在 JavaScript 表中选择动态链接。这是我尝试单击的链接之一的示例 HTML 代码:

<a href="#" onclick="javascript: runCategoryReport(0,&quot;objectName=enrollee&amp;titleMessageKey=3-3-2&amp;time=month&amp;systemTypeMetaId=6&amp;categoryName=Attendee&quot;);">1925</a>

我已经分别尝试了以下代码行来点击这个特定的链接:

选项 1

driver.find_element_by_xpath("//a/*[contains(text(), '3-3-2')]").click()

选项 2

driver.find_element_by_xpath("//a[contains(@onclick, '3-3-2')]").click()

两行代码都会出错:

NoSuchElementException: Message: no such element: Unable to locate element {"method":"xpath","selector":"//a/*[contains(text(), '3-3-2')]"} (Session info: chrome=90.0.4430.212)

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[contains(@onclick, '3-3-2')]"}
  (Session info: chrome=90.0.4430.212)

如果您对此问题提出任何反馈意见,我将不胜感激。

【问题讨论】:

    标签: javascript python pandas selenium-webdriver


    【解决方案1】:

    尝试使用attribute CSS selector:a[onclick*='3-3-2'],这将找到一个a标签,该标签的属性onclick包含'3-3-2'

    driver.find_element_by_css_selector("a[onclick*='3-3-2']").click()
    

    【讨论】:

    • 感谢您的推荐!我试了一下,不幸收到类似于我上面提到的错误: NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"a[onclick*=' 3-3-2']"}(会话信息:chrome=90.0.4430.212)
    • @RussellC 尝试等待元素出现。请参阅this 帖子。
    【解决方案2】:

    我能够解决我的问题。我添加了switch_to.frame 代码并将find_element_by_xpath 路径替换为链接的完整xpath。

    这是供任何人参考的最终代码:

    driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
    
    driver.find_element_by_xpath("/html/body/div/table/tbody/tr/td/form[1]/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr/td/table/tbody/tr[4]/td[2]/div/font/a").click()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-06
      • 2021-07-10
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多