且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Selenium - 使用 xpath 获取文本节点并将其用作 Java 中的字符串

更新时间:2023-11-07 11:45:22

我不确定我是否知道执行此操作的***方法,但这是一种方法.问题是您正在寻找一组元素中的特定文本,这些元素是包装器 DIV 的子元素.在您提供的示例中,我唯一能看到的是您想要的文本在包含标签之外.我们可以利用它来发挥我们的优势.基本上,该方法是获取包装器内的整个文本,然后遍历包装器的所有子元素,从原始字符串中删除每个子元素中包含的文本.那应该留下你想要的文字.我已经使用您提供的示例测试了以下代码.

String wrapperText = driver.findElement(By.id("wrapper")).getText().trim();//获取包装器下的所有文本列表children = driver.findElements(By.cssSelector("#wrapper > *"));//获取wrapper的所有子元素for (WebElement child : children){String subText = child.getText();//从子元素中获取文本wrapperText = wrapperText.replace(subText, "").trim();//从包装文本中移除子文本}System.out.println(wrapperText);

I have a section of code like this:

<div id='wrapper'>
  <span>*</span>    
  Question 1
</div>

I want to store the Question 1 as a string in Java so when I use the xpath //div/text() to get the text "Question 1." However when I try to print the value, I am getting the error Invalid Selector Exception Xpath //div/text() is: [object Text]. It should be an element.

String text = driver.findElement(By.xpath("//div")).getText();

//returns *Question 1

String text = driver.findElement(By.xpath("//div/text()")).getText();

//returns error

How am I supposed to store just the Question 1. I can replace the * once I get it using the first method above but I don't want to do that.

I'm not sure I know the best way to do this but this is a way. The issue is that you are looking for specific text within a group of elements that are children of the wrapper DIV. The only thing I can see in the example that you provided is that the text you want is outside of a containing tag. We can use that to our advantage. Basically the approach is to grab the entirety of the text inside wrapper and then loop through all child elements of wrapper removing the text contained within each from the original string. That should leave the text that you want. I have tested the code below using the example you provided.

String wrapperText = driver.findElement(By.id("wrapper")).getText().trim(); // get all the text under wrapper
List<WebElement> children = driver.findElements(By.cssSelector("#wrapper > *")); // get all the child elements of wrapper
for (WebElement child : children)
{
    String subText = child.getText(); // get the text from the child element
    wrapperText = wrapperText.replace(subText, "").trim(); // remove the child text from the wrapper text
}
System.out.println(wrapperText);