为 Selenium 编写正确的 Xpath:导致问题的预标记

Writing a Proper Xpath for Selenium: pre Tag Causing Problems

使用 Selenium 并尝试使用正确的 xpath 从 pre 标记中获取文本。

WebElement sequence = driver.findElement(By.xpath("//span[@id='MFE_sequence_span']/pre"));
WebElement structure = driver.findElement(By.xpath("//span[@id='MFE_structure_span']/pre"));
if(sequence.isDisplayed()) {
    System.out.println("sequence: " + sequence.getText());
    System.out.println("structure: " + structure.getText());
    break;
}

所以我 运行 进行了一些测试,它对其他标签工作得很好,当最后一个“/pre”不存在时,但是当我添加“/pre”时,我无法查找节点异常。这到底是怎么回事?

这是 html。真的很简单。是的,还有更多;这是嵌入的,但它是唯一相关的部分。

<span id="MFE_sequence_span">
<pre>
1      AAAAA
</pre>
</span>

那就不用担心标签了。只需使用 xpath 基于文本的搜索即可找到它。我总是发现在查找元素时会跳过很多问题。使用 explicit 等待,因为它是一个独立于标签的搜索,搜索速度可能较慢。

By byXpath = By.xpath("//*[.='1      AAAAA']");

WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(byXpath ));

编辑

我可以建议的另一件事是使用 JavaScript

//Just to make sure the previous tag is present
By byId = By.id("MFE_sequence_spa");
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(byId));

WebElement myDynamicElement = (WebElement)((JavascriptExecutor)driver).executeScript("return document.querySelector('#MFE_sequence_span>pre');");
System.out.println(myDynamicElement.getText());

打印

1      AAAAA

这可能不太成功,但请尝试用 div 替换跨度。

那是因为根据HTML规范,一个内联元素只能包含其他内联元素。由于 span 是内联的且 pre 是块,因此 span 内的 pre 无效 HTML.

好的,在对我得到的源进行进一步分析后,brunobastosg 是完全正确的。除了 span 内的 pre 标记之外,所有源都已被 Web 驱动程序获取。但是,pre 标记显然位于我浏览器的页面源代码中。因此,在我开始处理它之前,我假设 Selenium "correcting" 是坏的 html,从而造成这种巨大的烦恼。

我假设这是一个 Selenium 的东西,并查看其他库。好的部分是,出于许多其他原因,Selenium 仍然很有用。我可能只需要使用另一个库来进行实际的 html 处理,其中至少有一些我可以检查。如果我能找到解决方案,我会带着我的解决方案回到这里。

编辑

Saifur 在他的编辑中得到了它。问题已解决。