3

页面: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 但它显示

文档.评估

函数评估(){[本机代码]}

delete document.evaluate没有帮助,那么还有什么可以打破的document.evaluate呢?

4

1 回答 1

4

您在问题中显示的页面使用 xhtml 命名空间,您看到发生这种情况的其他页面可能也是如此。

由于您正在null为命名空间解析器参数设置它无法找到元素。

使用 XPath 的 MDN

注意:XPath 定义不带前缀的 QName 以仅匹配空名称空间中的元素。XPath 中无法获取应用于常规元素引用的默认命名空间(例如,p[@id='_myid'] for xmlns=' http://www.w3.org/1999/xhtml ') . 要匹配非空命名空间中的默认元素,您要么必须使用 ['namespace-uri()=' http://www.w3.org/1999/xhtml ' 和名称这样的形式来引用特定元素()='p' 和 @id='_myid'] (这种方法适用于可能不知道命名空间的动态 XPath)或使用前缀名称测试,并创建一个命名空间解析器,将前缀映射到命名空间。

因此,如果您设置了一个解析器,那么您可以通过为其添加前缀来正确访问该元素:

function resolver(prefix){
   return prefix === "xhtml" ? 'http://www.w3.org/1999/xhtml' : null;
}

document.evaluate("//xhtml:a",document,resolver,9,null).singleNodeValue

.evaluate 文档

创建解析器

如果你想在不知道命名空间的情况下获取一个节点,你可以使用local-name()XPath 函数作为表达式的一部分

document.evaluate("//*[local-name()='img']",document,null,9,null).singleNodeValue
于 2013-10-02T21:32:39.823 回答