document.evaluate allways returns null in singleNodeValue on some pages\\sites

青春壹個敷衍的年華 提交于 2019-12-06 03:48:46

The page you show in your question uses an xhtml namespace and probably so do the other pages that you are seeing this happen on.

Since you are setting null for the namespace resolver argument it cannot find the elements.

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.

So if you setup a resolver than you can access the element correctly by prefixing them:

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

If you want to get a node without having to know the namespace you can use local-name() XPath function as part of the expression

document.evaluate("//*[local-name()='img']",document,null,9,null).singleNodeValue
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!