【问题标题】:How can I identify an XPath without regard to div indices?如何在不考虑 div 索引的情况下识别 XPath?
【发布时间】:2021-04-25 15:11:18
【问题描述】:

我正在编写一个从网站上抓取信息的 python 代码,但我必须首先摆脱一些 cookie 弹出窗口。要单击正确的按钮,我需要它们的 XPath(据我所知)。问题是 XPath 的一部分每次都在变化,我不知道如何找到它们,因为它们实际上没有任何属性,如 ID 或其他东西。

这是按钮的 HTML:

<button class="Button__StyledButton-a1qza5-0 lcqSKB" style="visibility: visible; background-color: rgb(12, 44, 91);">Lees meer om voorkeuren te accepteren</button>

这是我现在使用的命令:

driver.find_element_by_xpath('/html/body/div[14]/div[1]/div[3]/button').click()

这是 XPath:

/html/body/div[VARIABLE]/div[1]/div[3]/button

其中 VARIABLE 每次都会更改,所以我更改了 14。

【问题讨论】:

    标签: python html xml selenium xpath


    【解决方案1】:

    这个 XPath,

    //button[.='Lees meer om voorkeuren te accepteren']
    

    将选择字符串值为'Lees meer om voorkeuren te accepteren'的所有按钮,与DOM层次结构中的布局或位置无关。

    您可以通过比较空白规范化字符串值使其更加健壮:

    //button[normalize-space()='Lees meer om voorkeuren te accepteren']
    

    这将在删除前导和尾随空格并将多个连续的内部空格折叠为单个空格后针对字符串值进行测试。

    【讨论】:

      【解决方案2】:

      如果您像现在这样使用完整的 xPath,您将一直遇到类似的问题。更好的方法是找出另一种/更短的方法来到达该元素。

      没有 URL 很难测试,但请尝试以下方法之一:

      driver.find_element_by_css_selector("Button__StyledButton-a1qza5-0.lcqSKB")
      driver.find_element_by_css_selector("Button__StyledButton-a1qza5-0")
      

      【讨论】:

        猜你喜欢
        • 2013-08-22
        • 1970-01-01
        • 1970-01-01
        • 2015-02-28
        • 2011-10-09
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多