页面:http://h4z.it/View/-20100729_designtea.jpg
在控制台中执行的代码:
document.evaluate("//img",document,null,9,null).singleNodeValue
或
document.evaluate("//a",document,null,9,null).singleNodeValue
甚至
document.evaluate("//html",document,null,9,null).singleNodeValue
结果(同时使用 Chrome 和 Firefox 进行测试):null
我认为该页面覆盖了 document.evaluate 但它显示了
document.evaluate
function evaluate() { [native code] }
和 delete document.evaluate
没有帮助,那么还有什么可以破坏 document.evaluate
呢?
最佳答案
您在问题中显示的页面使用 xhtml namespace ,您看到的其他页面可能也是如此。
由于您为 namespace 解析器参数设置了 null
,因此它找不到元素。
Note: XPath defines QNames without a prefix to match only elements in the null namespace. There is no way in XPath to pick up the default namespace as applied to a regular element reference (e.g., p[@id='_myid'] for xmlns='http://www.w3.org/1999/xhtml'). To match default elements in a non-null namespace, you either have to refer to a particular element using a form such as ['namespace-uri()='http://www.w3.org/1999/xhtml' and name()='p' and @id='_myid'] (this approach works well for dynamic XPath's where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace.
因此,如果您设置了一个解析器,那么您可以通过为它们添加前缀来正确访问该元素:
function resolver(prefix){
return prefix === "xhtml" ? 'http://www.w3.org/1999/xhtml' : null;
}
document.evaluate("//xhtml:a",document,resolver,9,null).singleNodeValue
如果您想在不知道命名空间的情况下获取节点,您可以使用 local-name()
XPath 函数作为表达式的一部分
document.evaluate("//*[local-name()='img']",document,null,9,null).singleNodeValue
关于javascript - document.evaluate 总是在某些页面\站点的 singleNodeValue 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19146056/