当“xmlns"出现时,Selenium 无法找到 Xpath包含属性 [英] Selenium cannot find Xpath when "xmlns" attribute is included
问题描述
基本上我正在尝试使用 Selenium 的 Xpath 处理以下 HTML:
<html xmlns="http://www.w3.org/1999/xhtml"><a>公共资料</a></html>
我正在使用以下选择器:
//a[text() = '公开资料']
看起来很简单,但是,根据 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/XPath 处理而言,xmlns="http://www.w3.org/1999/xhtml"
部分将 html
元素放入 XML 命名空间.
并且 a
元素继承了该命名空间.而 //a[text() = 'Public Profile']
XPath 表达式只会匹配一个 un-namespaced a
元素.>
//a[namespace-uri()='http://www.w3.org/1999/xhtml'][text() = 'Public Profile']
是一种方法使其匹配.
//*[name()='a'][text() = 'Public Profile']
是另一种方式.
并且 //*[text() = 'Public Profile']
是另一种方式(假设您已经知道这将获得您想要的 a
元素,而不是其他一些元素).
Basically I'm trying to process the following HTML using the Xpath of Selenium:
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<a>Public Profile</a>
</html>
I'm using the following selector:
//a[text() = 'Public Profile']
Seems simple enough, however, according to Selenium it returns 0 matches. I have tried in the online xpath tester as well:
and it doesn't return any results neither. The strange thing is that when I remove the
xmlns="http://www.w3.org/1999/xhtml"
-attribute it finds the match without a problem.
Can anyone explain to me why the xmlns tag makes the Xpath query fail?
On a sidenote, my C# selenium-xpath query looks the following:
Driver.FindElement(By.XPath("//a[text() = 'Public Profile']"))
EDIT: A link I found which explains what's going on nicely:
As far as XML/XPath processing goes, the xmlns="http://www.w3.org/1999/xhtml"
part puts the html
element into an XML namespace.
And the a
element inherits that namespace. And the //a[text() = 'Public Profile']
XPath expression will only match an un-namespaced a
element.
//a[namespace-uri()='http://www.w3.org/1999/xhtml'][text() = 'Public Profile']
is one way to make it match.
//*[name()='a'][text() = 'Public Profile']
is another way.
And //*[text() = 'Public Profile']
is yet another way (assuming you already know that’ll get the a
element you want, and not some other element).
这篇关于当“xmlns"出现时,Selenium 无法找到 Xpath包含属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!