【问题标题】:Python Selenium XPATH with multiple tags具有多个标签的 Python Selenium XPATH
【发布时间】:2019-02-23 09:43:45
【问题描述】:

我有一个自动 python 脚本来检查 DOM 中的任何更改。我有一个有效的 xpath:

//td[@class='high-bg']/a[@class='link-action'][@data-hintbox='1'][@data-hintbox-static='1'][@role='button'][@href='javascript:void(0)']

但它给了我比我需要的更多的输出,其中一些会导致错误。所以我想从 xpath 中获取我需要的抽象项目,所以我尝试使用这样的东西:

//table[@id't5c711109b1eea263276674']/tbody[]/tr[]/td[@class='warning-bg']/a[@class='link-action'][@data-hintbox='1'][@data-hintbox-static='1'][@role='button'][@href='javascript:void(0)']

但它不起作用,那么甚至可以搜索带有那么多标签的xpath吗?

<table id="example">
    <tbody>
        <tr>
            <td class="average-bg">
                <a class="link-action" data-hintbox="1" data-hintbox-static="1" role="button"                   href="javascript:void(0)">1</a>
            </td>
        </tr>
    </tbody>
</table>

【问题讨论】:

  • 能否将html图片替换为文本格式的html

标签: python selenium xpath webdriver xpath-1.0


【解决方案1】:

关于您的代码试验:

  • 在您的第一次尝试中,您尝试使用元素的所有属性来构造 xpath

    //td[@class='high-bg']/a[@class='link-action'][@data-hintbox='1'][@data-hintbox-static='1'][@role='button'][@href='javascript:void(0)']
    
  • 具有相似属性的元素可以存在但在不同的位置/位置。因此,它返回的输出超出了您的预期。

  • 在您的第二次尝试中,您构建了一个 absolute xpath,它是易碎的

    //table[@id't5c711109b1eea263276674']/tbody[]/tr[]/td[@class='warning-bg']/a[@class='link-action'][@data-hintbox='1'][@data-hintbox-static='1'][@role='button'][@href='javascript:void(0)']
    

解决方案

根据您提供的基于文本的 HTML,要识别所需的元素,您可以使用以下任一解决方案:

  • xpath:

    driver.find_element_by_xpath("//table[@id='example']//td[@class='average-bg']/a[@class='link-action' and text()='1']")
    
  • css_selector:

    driver.find_element_by_css_selector("table#example td.average-bg>a.link-action")
    

【讨论】:

  • 谢谢!我找到了另一种解决方法,但是您为我解决了一些问题,非常感谢!
【解决方案2】:

在这里。

XML

<root>
  <e1 role='a' class='y'></e1>
  <e1 role='a' class='t'></e1>
  <e1 role='a' class='z'></e1>
</root>

XAPTH

//e1[@role='a' and @class='t']

输出

Element='<e1 class="t" role="a"/>'

【讨论】:

  • 是的,我明白了,谢谢。但是如果你的根目录中有一个表,我可以以某种方式导航到我需要的元素吗?如果它真的很深
  • 我想你可以。为什么不呢?
  • 假设我的元素在 e1 元素中,我将如何在我的 xpath 中表示它?
猜你喜欢
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 2017-12-06
  • 1970-01-01
  • 2021-10-20
  • 2010-10-17
  • 2015-09-28
相关资源
最近更新 更多