【问题标题】:Python selenium xpath descendantPython selenium xpath 后代
【发布时间】:2020-07-30 16:35:45
【问题描述】:

有谁知道如何获取按钮:

svg[@aria-label='Like']

截图如下:

我尝试了各种组合...没有任何效果。 我曾与:

//button[@class='wpO6b ']

但我不想再使用它了。 所以我的尝试:

//button[@class='wpO6b ']/descendant::svg[@aria-label='Like']
//button[@class='wpO6b' and descendant::svg[@aria-label='Like']]
//button[@class='wpO6b ']//svg[@aria-label='Like']

感谢阅读!

编辑:我想点击按钮元素。

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver xpath


    【解决方案1】:

    在您的代码中尝试以下xpath -

    driver.find_element_by_xpath('//*[local-name()="svg" and @aria-label="Like"]/parent::span/parent::div/parent::button').click()
    

    希望它能检测到按钮。让我知道结果。

    【讨论】:

    • 没有用。但谢谢你的想法。我应该说我想点击元素。
    • 我已经给了你按钮本身.. 在XPath 中,我首先提到了 svg 元素,然后返回直到按钮被选中,然后我点击了相同的按钮。我已经通过点击更新了我的代码。请尝试一下,如果这是您要找的,请告诉我?
    • 代码更新,现在试试看。
    • @raphi195 看起来有点乱。尝试简化为driver.find_element_by_xpath('//button[.//*[name()="svg" and @aria-label="Like"]]').click()
    【解决方案2】:

    为什么这些不起作用:

    //button[@class='wpO6b ']/descendant::svg[@aria-label='Like']
    //button[@class='wpO6b ']//svg[@aria-label='Like']
    

    您选择了svg 元素而不是按钮。您必须将 svg 部分放在谓词中。

    //button[@class='wpO6b' and descendant::svg[@aria-label='Like']]
    

    这个几乎不错,但由于button 元素的class 属性中有一个空格,所以它不起作用。可以使用contains 函数进行相应修复,这是一个更安全的选项:

    //button[contains(@class,'wpO6b') and descendant::svg[@aria-label='Like']]
    

    另一种选择按钮的方式(使用ancestor 轴和更强大的谓词):

    //svg[@aria-label="Like" and @fill="#262626"]/ancestor::button[1][contains(@class,"wpO6b")]
    

    如果您正在处理namespaces,请使用以下表达式:

    //*[local-name()='button'][contains(@class,'wpO6b') and descendant::*[local-name()='svg'][@aria-label='Like']]
    

    【讨论】:

      【解决方案3】:

      你可以写xpath:

      //svg[@aria-label='Like']/ancestor::button[1]
      

      【讨论】:

      • 它应该在不同的 xpath 轴的帮助下以不同的方式工作。 guru99.com/… 中有关如何编写 xpath 的更多详细信息
      • 你能分享你试图获取元素的网址吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 2014-09-01
      • 2021-10-31
      • 2017-11-17
      相关资源
      最近更新 更多