【问题标题】:unable to find multiple existing element with selenium无法用硒找到多个现有元素
【发布时间】:2021-03-02 13:34:58
【问题描述】:

这是我试图点击的链接的 html 代码(我不知道为什么 selenium 无法找到链接。我的猜测是,有 X 数量的链接。唯一的区别是括号中的字符串onclick。)在下面,我将向您展示 2 个 html 代码示例。我想点击所有这些(在这种情况下同时点击)!

  1. 按钮或链接:

    <td class="text-right">
      <a href="#"onclick="doRetrievePnr('DUA75J')"  id="viewPnr">Ansehen</a></td>
  2. 按钮或链接:

<td class="text-right">
  <a href="#" onclick="doRetrievePnr('C574DC')" id="viewPnr">Ansehen</a></td>

这是我点击按钮的尝试:

  1. driver.find_element_by_link_text("doRetrievePnr('DUA75J')").click()
  2. driver.find_element_by_xpath("//a[@onclick='doRetrievePnr('DUA75J')']").click()

这是我得到的错误:

  1. selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"doRetrievePnr('DUA75J')"}

  2. selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //a[@onclick='doRetrievePnr('DUA75J')'] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//a[@onclick='doRetrievePnr('DUA75J')']' is not a valid XPath expression.

我错过了什么吗?

编辑 Heres a picture of the BUTTONS, the HTML CODE and my PYTHON CODE (lines 34 & 35)

【问题讨论】:

  • By_Link_text 是链接文本,这是标签之间的位,即Ansehen ...您的 xpath 您遇到了引用问题。看起来单引号太多了,我预计它会在中途终止。很高兴查看页面并反馈答案,您可以分享指向它的链接吗?
  • @RichEdwards 我必须登录该网站才能看到它。但我会尝试用 html 代码截取页面!请稍等。
  • 如果你想点击所有这些,你可以做find_elements(注意它是复数) - 并使用 id viewPnr - 然后遍历结果以与每个交互
  • @RichEdwards 我添加了更详细的图片!与此同时,我将尝试复数方法。我以前试过,但这次我可以做到。

标签: html python-3.x selenium selenium-chromedriver


【解决方案1】:

如 cmets 中所述 - 获取特定标识符的所有项目可以使用 find_elements_by_... 完成(注意 find elements - 它是复数)

这会返回一个数组,您可以遍历它以与每个元素进行交互。

您的所有链接似乎都具有相同的 ID。

这样的事情可能会奏效:

links = driver.find_elements_by_id('viewPnr')
for link in links:
    link.click()
    time.sleep(10) #replace this with what you want to do

显然,如果您单击链接并且页面发生更改,则在第一次迭代后可能无法正常工作。但是,这是关于如何获取所有对象并遍历它们的概念。

【讨论】:

  • 我想我明白了!我会尝试一下,我会告诉你它是否有效。给我一点时间:D
猜你喜欢
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 2022-01-23
  • 2021-08-15
相关资源
最近更新 更多