如何使用量角器xpath函数仅从父元素(不包括子元素)获取文本?

时间:2019-05-03 11:02:20

标签: xpath

我正在尝试仅获取具有一个或多个子代的父元素的文本。如何使用XPath获得它?

(我将上述XPath与量角器的getText()方法一起用作元素标识符)

父元素的文本根据用户语言选择而变化,所以我更喜欢使用id属性来标识元素

*<div class="header" id="Welcome_Label">
    "Welcome to the Mail page"
  <button class="btn" id="open">
    Open
    </button>
</div>*

xpath尝试获取父文本为

//div[@id='Welcome_Label']/*[not(self::button)]

我希望它返回文本父文本“ Welcome to the Mail page”,但返回“ Welcome to the Mail page Open”。

4 个答案:

答案 0 :(得分:0)

除非我仅使用您的代码就丢失了某些东西

//div/text()

输出:

  

“欢迎使用邮件页面”

这是您要找的吗?

答案 1 :(得分:0)

欢迎来到。

如果您正在使用仅从父节点获取文本的方法。

Python实现:

def get_text_exclude_children(element):
return driver.execute_script(
    """
    var parent = arguments[0];
    var child = parent.firstChild;
    var textValue = "";
    while(child) {
        if (child.nodeType === Node.TEXT_NODE)
                textValue += child.textContent;
                child = child.nextSibling;
    }
    return textValue;""",
    element).strip()

在这种情况下,您可以按以下方式调用它。

ele = driver.find_element_by_css_selector(".header")
value = get_text_exclude_children(ele)
print (value)

Java实现:

public String get_text_exclude_children(WebDriver driver, WebElement element) {
    JavascriptExecutor js = (JavascriptExecutor) driver;  
    return (String) js.executeScript("var parent = arguments[0];"
                                    + "var child = parent.firstChild;"
                                    + " var textValue = ''; while(child) { "
                                            + "if (child.nodeType === Node.TEXT_NODE)"
                                                + " textValue += child.textContent;"
                                                + " child = child.nextSibling; "
                                                + "} return textValue;",element);

答案 2 :(得分:0)

您可以尝试

//div[@id='Welcome_Label']/text()[../*]

如果它具有至少一个子元素,它将选择text()级别的所有div节点。

答案 3 :(得分:0)

我有一个类似的问题,发现以下问题:http://exploreselenium.com/selenium/exclude-text-content-of-child-elements-of-the-parent-element-in-selenium-webdriver/

使用它,我只是添加了以下功能,尽管在这种情况下,我使用CSS而不是XPath。

async function getTextExcludingChildren(css: string) {
    return await browser.executeScript(`return $("${css}").clone().children().remove().end().text();`);
}
相关问题