我这里有这个 html 片段。
这就是我想要实现的,用户输入一个值后,使用输入值检查哪个PagePostsSectionPaglet包含它,找到PagePostsSectionPaglet并找到 className("_5sem")
即在同一个 PagePostsSectionPaglet 中
get a list of text from webelement
//compare a list of text in PagePostsSectionPaglet with unknown user input
if text in PagePostsSectionPaglet = input year
{
find PagePostsSectionPaglet that contains text that is same with input year
go through same PagePostsSectionPaglet and find className="_5sem">
{
find UFIPagerLink //inside class="_5sem"
find UFIPagerIcon //inside class="_5sem"
}
}
问题如何找到包含用户输入“文本”而不是特定值的网页元素 PagePostsSectionPagelet?
尝试了不同的方法,但都出现了这个SyntaxError: The expression is not a legal expression.
List <WebElement> PagePostsSectionPagelet = elm.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]//contains('"+elm.getText()+"')"));
List <WebElement> PagePostsSectionPagelet = elm.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]//span[elm.getText()]"));
我的代码
//tried to print the list of texts in AllPagePostsSectionPagelet but only returns the first value
List <WebElement> AllPagePostsSectionPagelet= dr.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]//span[@class='_5em9 lfloat _ohe _50f4 _50f7']"));
for (WebElement elm : AllPagePostsSectionPagelet){
if(year.equals(elm.getText())){ //year is the user input value
//get weblement that contains the text
List <WebElement> PagePostsSectionPagelet = elm.findElements(By.xpath("//*[starts-with(@id, 'PagePostsSectionPagelet')]//elm.getText()")); //this is the issue
System.out.println(PagePostsSectionPagelet);
for (WebElement elment : PagePostsSectionPagelet){
List<WebElement> comments = elment.findElements(By.className("_5sem")); //find web element
//iterate through the comments
for (WebElement comment : comments) {
//find web elements by their respective class name
List<WebElement> commentsbutton = comment.findElements(By.className("UFIPagerLink"));
List<WebElement> repliesbutton = comment.findElements(By.className("UFIPagerIcon"));
}
}
//return;
}
}
最佳答案
这是我从你的问题中了解到的(如果我错了请纠正我),你正在尝试搜索满足 2 个条件的特定 div
标签:
- 有一个
id="PagePostsSectionPagelet"
- 并且在该标签内应该有一个
span
标签,它与用户输入的值相匹配(例如:2014)
现在,在那个 div
标签中,您想要使用 class="_5sem"
获取另一个 div
标签。
如果我所解释的与您想要实现的相匹配,那么下面给出的 xpath 应该适用于您在上面提供的 HTML 源。
"//span[text()='2014']/ancestor::div[contains(@id, 'PagePostsSectionPagelet')]//div[@class='_5sem']"
您提供的 Java 代码可以简化为:
//year is the user input value
String xp = "//span[text()='" + year + "']/ancestor::div[contains(@id, 'PagePostsSectionPagelet')]//div[@class='_5sem']";
WebElement comment = driver.findElement(By.xpath(xp));
// Add code to fetch 'UFIPagerLink' and 'UFIPagerIcon'
// which should be inside the div tag with class="_5sem"
关于java - 查找包含未知跨度文本的网络元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594628/