[英]How do I get all child nodes of an element , including text ones, in Selenium WebElement?
I have to parse this element in a Java Selenium application:我必须在 Java Selenium 应用程序中解析这个元素:
<span class="text-small-teaser d-none d-sm-inline-block cut-job-address swissdev-grey-text">
<span class="icon-building mr-1" aria-hidden="true"></span>
<span class="mr-3">Altex Romania </span>
<span class="icon-map-marker mr-1" aria-hidden="true"></span>
Global City Business Park, Bucharest
<span class="green-text"> + Remote</span>
</span>
I want to get a list with all its 5 children, including the text one.我想得到一个包含所有 5 个孩子的列表,包括文本之一。 When I use any selector from WebElement, either xpath, cssSelector, it only returns me the 4 non-text elements.
当我使用 WebElement 中的任何选择器时,无论是 xpath、cssSelector,它只会返回 4 个非文本元素。 Does anyone know how to do that?
有谁知道这是怎么做到的吗? I'm a newbie with Selenium, i haven't worked with it before.
我是 Selenium 的新手,我以前没有使用过它。 Thanks.
谢谢。
Global City Business Park, Bucharest
is NOT a child node of the parent span
node like the other 4 span
nodes. Global City Business Park, Bucharest
与其他 4 个span
节点不同,它不是父span
节点的子节点。
This text value is a text of the parent node itself.该文本值是父节点本身的文本。
So if for example, you want to extract the text of the second child Altex Romania
you will be able to locate the second child element with XPath like this因此,例如,如果您想提取第二个子
Altex Romania
的文本,您将能够像这样使用 XPath 定位第二个子元素
"//span[contains(@class,'cut-job-address')]//span[@class='mr-3']"
And extract the text from that WebElement
object.并从该
WebElement
object 中提取文本。
However to extract the Global City Business Park, Bucharest
you will have to extract the text from parent element itself, something like this:但是,要提取
Global City Business Park, Bucharest
您必须从父元素本身提取文本,如下所示:
WebElement element = driver.findElement(By.xpath("//span[contains(@class,'cut-job-address')]"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
String parentStringOnly = jse.executeScript("""
return jQuery(arguments[0]).contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
""", element);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.