在CSS选择器中使用文本查找链接不起作用

时间:2018-11-17 12:00:39

标签: selenium selenium-webdriver css-selectors webdriver

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

我知道可以通过使用XPath或其他方式来实现,但是我很好奇为什么我使用的CSS Selector无法正常工作。请参阅此link

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

3 个答案:

答案 0 :(得分:1)

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

a[title="seleniumframework"]

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

您也可以使用以下命令:a[target="_blank"],但是上面的命令更为独特。

希望对您有帮助!

答案 1 :(得分:1)

您正尝试使用以下 CssSelector s查找链接:

  • 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']"
    

答案 2 :(得分:0)

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

文本在html中不可用,因此无法通过CSS如此选择。相反,您应尝试使用其他属性,例如a [title = seleniumframework]。