Selenium WebDriver - select 跨度和排除子节点的 Xpath
Selenium WebDriver - Xpath to select span and exclude a child node
我今天问了问题,但是我错误地没有指定它的范围,它是在Selenium Webdriver中使用的。
所以我有这个 td:
<td>
<span id="PartComment">
REMAN WATER PUMP
<i>w/2.05" DIAMETER THERMOSTAT OUTLET - SUPPLIED w/PULLEY
</i>
</span>
</td>
我希望 xpath 仅定位文本 REMAN WATER PUMP 以便稍后将其转换为字符串。
driver.findElement(By.xpath("//span[@id='lblPartComment']/text()"));
但问题是,由于我只是定位文本,而不是 DOM 对象,WebDriver 将无法这样处理它:
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: The given selector //span[@id='lblPartComment']/text() is either invalid or does not result in a WebElement. The following error occurred: InvalidSelectorError: The result of the xpath expression "//span[@id='lblPartComment']/text()" is: [object Text]. It should be an element.
您能否提供该 xpath 的替代方案?一个找到我上面提到的文本,并排除 i
?
中的文本
此外,related。
谢谢
您可以使用以下代码:
var firstText = this.Driver.FindElement(By.XPath("//span[@id='lblPartComment']")).Text;
var firstChildText = this.Driver.FindElement(By.XPath("//span[@id='lblPartComment']/i")).Text;
firstText = firstText.Replace(firstChildText, string.Empty);
找到父元素和子元素,获取它们的文本并将子元素的文本替换为空字符串。 :)
你可以做到。来自 this
JavascriptExecutor js = (JavascriptExecutor) driver;
String text = (String) js.executeScript("var parent = arguments[0];"
+ "var child = parent.firstChild;"
+ "var ret = \"\";"
+ "while(child) {"
+ " if (child.nodeType === Node.TEXT_NODE)"
+ " ret += child.textContent;"
+ " child = child.nextSibling;"
+ "}"
+ "return ret;", driver.findElement(By.id("PartComment")));
我今天问了
所以我有这个 td:
<td>
<span id="PartComment">
REMAN WATER PUMP
<i>w/2.05" DIAMETER THERMOSTAT OUTLET - SUPPLIED w/PULLEY
</i>
</span>
</td>
我希望 xpath 仅定位文本 REMAN WATER PUMP 以便稍后将其转换为字符串。
driver.findElement(By.xpath("//span[@id='lblPartComment']/text()"));
但问题是,由于我只是定位文本,而不是 DOM 对象,WebDriver 将无法这样处理它:
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: The given selector //span[@id='lblPartComment']/text() is either invalid or does not result in a WebElement. The following error occurred: InvalidSelectorError: The result of the xpath expression "//span[@id='lblPartComment']/text()" is: [object Text]. It should be an element.
您能否提供该 xpath 的替代方案?一个找到我上面提到的文本,并排除 i
?
此外,related。
谢谢
您可以使用以下代码:
var firstText = this.Driver.FindElement(By.XPath("//span[@id='lblPartComment']")).Text;
var firstChildText = this.Driver.FindElement(By.XPath("//span[@id='lblPartComment']/i")).Text;
firstText = firstText.Replace(firstChildText, string.Empty);
找到父元素和子元素,获取它们的文本并将子元素的文本替换为空字符串。 :)
你可以做到。来自 this
JavascriptExecutor js = (JavascriptExecutor) driver;
String text = (String) js.executeScript("var parent = arguments[0];"
+ "var child = parent.firstChild;"
+ "var ret = \"\";"
+ "while(child) {"
+ " if (child.nodeType === Node.TEXT_NODE)"
+ " ret += child.textContent;"
+ " child = child.nextSibling;"
+ "}"
+ "return ret;", driver.findElement(By.id("PartComment")));