Selenium:使用Java中的cssSelector提取div的文本 [英] Selenium: Extract Text of a div with cssSelector in Java
问题描述
我正在使用Selenium为网页编写JUnit测试,我正在尝试验证页面中是否存在预期的文本。我正在测试的网页代码如下所示:
I am writing a JUnit test for a webpage, using Selenium, and I am trying to verify that the expected text exists within a page. The code of the webpage I am testing looks like this:
<div id="recipient_div_3" class="label_spacer">
<label class="nodisplay" for="Recipient_nickname"> recipient field: reqd info </label>
<span id="Recipient_nickname_div_2" class="required-field"> *</span>
Recipient:
</div>
我想比较预期与页面上的内容,所以我想使用
Assert.assertTrue()。我知道要从div中获取所有内容,我可以做到
I want to compare what is expected with what is on the page, so I want to use Assert.assertTrue(). I know that to get everything from the div, I can do
String element = driver.findElement(By.cssSelector("div[id='recipient_div_3']")).getText().replaceAll("\n", " ");
但这将返回reqd info * Recipient:
but this will return "reqd info * Recipient:"
有没有办法只使用cssSelector从div(Recipient)获取文本,而没有其他标签?
Is there any way to just get the text from the div ("Recipient") using cssSelector, without the other tags?
推荐答案
你不能用CSS选择器做到这一点,因为CSS选择器没有足够细粒度的方法来表达DIV中包含的文本节点而不是其他内容。但是,您可以使用XPath定位器执行此操作:
You can't do this with a CSS selector, because CSS selectors don't have a fine-grained enough approach to express "the text node contained in the DIV but not its other contents". You can do that with an XPath locator, though:
driver.findElement(By.xpath("//div[@id='recipient_div_3']/text()")).getText()
XPath表达式将识别只是单个文本节点,它是DIV的直接子节点,而不是其中包含的所有文本及其子节点。
That XPath expression will identify just the single text node that is a direct child of the DIV, rather than all the text contained within it and its child nodes.
这篇关于Selenium:使用Java中的cssSelector提取div的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!