<div id="blurb">
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. Join them; it only takes a minute:
<br>
<br>
<a href="/users/signup?ssrc=hero&returnurl=https%3a%2f%2fsqa.stackexchange.com%2f" id="tell-me-more" class="button">Join</a>
</div>
我有上面的 HTML 标记。我需要从父标签 div 节点中提取以下文本,不包括其子节点:
Software Quality Assurance & Testing Stack Exchange 是面向软件质量控制专家、自动化工程师和软件测试人员的问答网站。加入他们;只需一分钟:
但是,我正在使用xpath
也从子节点中提取Join
<a>
。
以下是我尝试xpath
:
//div[@id='blurb']/*[not(@id='tell-me-more')]
如何编写xpath
以仅从父节点而不是从其子节点中提取文本?
通常你会使用 //div[@id='blurb']/text()[1]
,但selenium
不支持这种语法,因为XPath
应该只返回WebElement
,而不是文本节点......
您可以使用JavaScriptExecutor
获得所需的输出:
WebElement myDiv = driver.findElement(By.id("blurb"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
String divText = (String) jse.executeScript("return arguments[0].childNodes[0].nodeValue;", myDiv);
我在下面的 xpath 中找到了答案,它起作用了:-
//div[@id='blurb']/*[not(self::a)]
在这里,我们省略了内部锚标签,一个内部的父 div 标签