xml - 包含 "xmlns"属性时,Selenium 找不到 Xpath

标签 xml selenium xpath

基本上我正在尝试使用 Selenium 的 Xpath 处理以下 HTML:

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<a>Public Profile</a>
</html>

我正在使用以下选择器:
//a[text() = 'Public Profile']

看起来很简单,但是,根据 Selenium,它返回 0 个匹配项。
我也尝试过在线 xpath 测试器:

http://codebeautify.org/Xpath-Tester



它也不返回任何结果。
奇怪的是,当我删除

xmlns="http://www.w3.org/1999/xhtml"



-attribute 它可以毫无问题地找到匹配项。

谁能向我解释为什么 xmlns 标签会使 Xpath 查询失败?

在旁注中,我的 C# selenium-xpath 查询如下所示:
Driver.FindElement(By.XPath("//a[text() = 'Public Profile']"))

编辑:我找到的一个链接很好地解释了发生了什么:

XML element has namespace, my XPATH does not work

最佳答案

就 XML/XPath 处理而言,xmlns="http://www.w3.org/1999/xhtml"部分放html元素放入 XML 命名空间。

a element 继承该命名空间。和 //a[text() = 'Public Profile'] XPath 表达式将只匹配未命名空间的 a元素。
//a[namespace-uri()='http://www.w3.org/1999/xhtml'][text() = 'Public Profile']是使其匹配的一种方法。
//*[name()='a'][text() = 'Public Profile']是另一种方式。

//*[text() = 'Public Profile']是另一种方式(假设您已经知道它将获得您想要的 a 元素,而不是其他一些元素)。

关于xml - 包含 "xmlns"属性时,Selenium 找不到 Xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232299/

相关文章:

python - 使用带有 Python 的 XSL FO 从 XML 创建 PDF

excel - 尝试使用 VBA 在 Chrome 中单击按钮

java - 使用x路径在java中加载xml

android - 尝试使软键盘输入按钮说搜索或显示搜索放大镜并处理其对 EditText 的点击

Xml Schema 验证,有效内容无效

xml - W3 和 xmlsoap.org 架构之间有什么区别?

java - 如何从PDF中读取条件文本?

java - 生成错误 : Cannot find the class file for org. openqa.selenium.internal.Locatable

java - org.openqa.selenium.NoSuchElementException : Unable to locate element error

html - 当 <a> 埋在另一个标签中时,使用 XPath 获取它的文本,例如<强>