javascript - document.evaluate 总是在某些页面\站点的 singleNodeValue 中返回 null

标签 javascript google-chrome firefox document.evaluate

页面: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,因此它找不到元素。

MDN Using XPath

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

.evaluate doc

Creating Resolver

如果您想在不知道命名空间的情况下获取节点,您可以使用 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/

相关文章:

javascript - Ag-Grid - 访问所有数据 - 包括计算列

javascript - 通过Javascript扩展修改Firefox标题栏

html - 如何让IE像Chrome和Firefox一样在p标签的顶部自动留白?

debugging - 使用 Chrome 进行 Webstorm 调试?

javascript - 通过命令行或本地脚本与浏览器 JavaScript 交互?

javascript - 如何在测试环境中的测试中设置 CasperJS 页面选项?

javascript - HTMLUnit 未使用 JavaScript 返回完全加载的页面

javascript - 无法访问复制到剪贴板的文本

javascript - Chrome Array.sorting 数字乱序

css - 我可以让为 OS X 上的 safari 编写的 CSS 在 chrome for windows 中工作吗?