基本上我正在尝试使用 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 测试器:
它也不返回任何结果。
奇怪的是,当我删除
xmlns="http://www.w3.org/1999/xhtml"
-attribute 它可以毫无问题地找到匹配项。
谁能向我解释为什么 xmlns 标签会使 Xpath 查询失败?
在旁注中,我的 C# selenium-xpath 查询如下所示:
Driver.FindElement(By.XPath("//a[text() = 'Public Profile']"))
编辑:我找到的一个链接很好地解释了发生了什么:
最佳答案
就 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/