【问题标题】:Extracting content in :after using XPath使用 XPath 提取 :after 中的内容
【发布时间】:2016-11-30 10:14:35
【问题描述】:

我正在尝试通过以下方式获取 CSS 属性“内容”的值:

WebElement plusOrMinusSign = currentEntityTypeLevel1.findElement(
    By.xpath("i[@class='tree-branch-head']::after"));
System.out.println(plusOrMinusSign.getCssValue("content"));

但是,我收到一个错误:The string 'i[@class='tree-branch-head']::after' is not a valid XPath expression.

似乎无法识别“::after”。

HTML:

<i class="tree-branch-head" ng-class="iBranchClass()" ng-click="selectNodeHead(node)">::after
</i>

CSS:

i:after {
    content: "-";
}

知道如何获得“内容”的价值吗?

【问题讨论】:

标签: css xpath selenium-webdriver pseudo-element


【解决方案1】:

您正在使用 By.xpath,但 i[@class='tree-branch-head']::after 不是有效的 XPath,它是 XPath 表示法 (i[@class='tree-branch-head']) 和 CSS (:after) 的混合体。

您应该使用By.cssSelector 和有效的CSS 选择器,例如i.tree-branch-head:after。如果 Selenium 接受伪元素,这将起作用,但它不接受。

要解决此问题,您可以使用 Chromium,它会生成额外的虚假元素 ::after 和 ::before,或者使用 https://stackoverflow.com/a/28265738/449288 中描述的 Javascript 提取器。

【讨论】:

  • 感谢 Gieole,您的 i.tree-branch-head:after 帮助我走上了正轨。这是用于检索“内容”值的字符串值。 String script = "return window.getComputedStyle(document.querySelector('i.tree-branch-head'),':after').getPropertyValue('content');";
【解决方案2】:

在 selenium webdriver 中处理伪元素

 String script = "return window.getComputedStyle(document.querySelector('Enter root class name here '),':after').getPropertyValue('content')";
            Thread.sleep(3000);
            JavascriptExecutor js = (JavascriptExecutor) driver;
            String content = (String) js.executeScript(script);
            System.out.println(content);

现在在您的断言命令或您想使用的任何地方使用此内容字符串,希望这对您有用...祝您好运

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-15
    • 2020-08-06
    • 2020-10-28
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    相关资源
    最近更新 更多