我有一个 html 代码,如下所示:
<h3> Some Heading </h3>
<p> Some String </p>
<p> more string </p>
<h3> Other heading</h3>
<p> some text </p>
我正在尝试访问Some String
, more string
和some text
。使用java,我尝试像这样访问:
List<WebElement> h3Tags = driver.findElements(By.tagName("h3"));
List<WebElement> para = null;
WebElement bagInfo = h3Tags.get(0); //reads first h3
if(bagInfo.getText().contains("carry-on") || bagInfo.getText().contains("Carry-on")){
para = AutoUtils.findElementsByTagName(bagInfo, "p");
System.out.println(para.get(0).getText()); //Null pointer here
}
bagInfo = h3Tags.get(1);
if(bagInfo.getText().contains("checked") || bagInfo.getText().contains("Checked")){
para = AutoUtils.findElementsByTagName(bagInfo, "p");
System.out.println(para.get(0).getText()); //Null pointer here too
}
尝试过xpath
喜欢 "h3['/p']"
但仍然没有运气。访问这些的最佳方式是什么 <p>
字符串?
最佳答案
尝试使用 xpath //h3/following-sibling::p
来匹配所有 3 个段落
另请注意,您的 XPath h3['/p']
不起作用,因为它意味着返回作为 DOM 根节点的 h3
节点。谓词 ['/p']
将始终返回 True,因为非空字符串('/p'
在您的情况下)始终为 True
关于java - 无法使用 selenium 读取 <h3> 下的 <p> 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48830749/