【问题标题】:Css Selector for the Log Out button注销按钮的 CSS 选择器
【发布时间】:2017-02-26 14:33:03
【问题描述】:

我在页面中有一个注销按钮。我正在尝试在 Selenium 中将其自动化。以下是该元素的源代码。

<a class="_2k0gmP" data-reactid="53" href="#">Log Out</a>

这是我正在使用的代码

driver.findElement(By.cssSelector("._2k0gmP[text='Log Out']"));

但我反复收到 No such Elemet found 异常,有时是 Invalid Selector Exception。有人可以帮我吗?

【问题讨论】:

    标签: selenium css-selectors


    【解决方案1】:

    您收到InvalidSelectorException 是因为您不能使用cssSelector 根据其内部HTML 文本查找元素。为此,您可以使用 xpath 或 linkText 选择器。

    xpath:driver.findElement(By.xpath(".//a[text()='Log Out']");

    链接文本:driver.findElement(By.linkText("Log Out"));

    NoSuchElement 异常可能被抛出,因为您在类选择器中遗漏了_,正如@gecki 所说,所以您的选择器正在搜索不存在的类。

    【讨论】:

    • 是的@acikojevic,linkText 选项确实有效。谢谢。
    【解决方案2】:

    不要省略下划线:

    driver.findElement(By.cssSelector("._2k0gmP[text='Log Out']"));
    

    但是,在这种情况下,我更喜欢

    driver.findElement(By.linkText("Log Out"));
    

    【讨论】:

    • 您无法定位使用 CSS 选择器包含的文本。
    • @Gecki,linkText 选择器确实有效。谢谢!!。
    【解决方案3】:

    xpath:

    driver.findElement(By.xpath("//a[text()='Log Out']");
    

    【讨论】:

    • 虽然这在理论上可以回答这个问题,但如果您提供答案的解释而不是仅提供代码答案会更好。
    猜你喜欢
    • 2017-07-11
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 2012-08-25
    • 2012-03-14
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多