【问题标题】:Finding link using text in CSS Selector is not working在 CSS 选择器中使用文本查找链接不起作用
【发布时间】:2019-04-20 10:04:11
【问题描述】:

我正在尝试使用a[text='This is a link']a[innertext='This is a link'] 定位下面的链接,但它们都不起作用。

我知道这可以通过使用 XPath 或其他方式来实现,但我很好奇为什么我使用的 CSS 选择器不起作用。参考这个link

<a title="seleniumframework" href="http://www.seleniumframework.com" target="_blank">This is a link</a>

【问题讨论】:

    标签: selenium selenium-webdriver css-selectors webdriver


    【解决方案1】:

    由于您尝试使用属性选择器,因此您只能从超链接元素当前具有的可用属性中进行选择。

    text 在 html 中是不可用的属性,因此通过 css 选择它是行不通的。相反,您应该尝试使用其他属性,例如 [title=seleniumframework]。

    【讨论】:

    • 那么 this //a[text()='This is a link'] xpath with text 是如何工作的?
    • XPath 中的@J_Coder text() 不是属性,而是返回文本节点的函数
    【解决方案2】:

    适合您的情况的正确 CSS 选择器是:

    a[title="seleniumframework"]
    

    a[href="http://www.seleniumframework.com"]
    

    你也可以用这个:a[target="_blank"],不过上面的比较独特。

    希望对你有帮助!

    【讨论】:

      【解决方案3】:

      您正在尝试使用以下 CssSelectors 来定位链接:

      • a[text='This is a link']
      • a[innertext='This is a link']

      根据Issue#987Issue#1547

      The :contains pseudo-class isn't in the CSS Spec and is not supported by either Firefox or Chrome (even outside WebDriver).

      您可以在selenium.common.exceptions.InvalidSelectorException with “span:contains('string')”找到详细讨论

      解决方案

      根据 HTML,您可以使用以下任一解决方案:

      • CssSelector 使用属性title:

        "a[title='seleniumframework']"
        
      • CssSelector 使用属性href:

        "a[href='http://www.seleniumframework.com']"
        
      • CssSelector 使用属性titlehref

        "a[title='seleniumframework'][href='http://www.seleniumframework.com']"
        

      【讨论】:

        猜你喜欢
        • 2014-03-01
        • 1970-01-01
        • 2014-10-20
        • 2021-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多