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

孤者浪人 提交于 2019-12-07 18:59:36

问题


page: http://h4z.it/View/-20100729_designtea.jpg

code to execute in console: document.evaluate("//img",document,null,9,null).singleNodeValue

or

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

or even

document.evaluate("//html",document,null,9,null).singleNodeValue

result (tested both with Chrome and Firefox): null

I thought that page overrided document.evaluate but it shows

document.evaluate

function evaluate() { [native code] }

and delete document.evaluate does not help, so what else can it be which breaks document.evaluate ?


回答1:


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


来源:https://stackoverflow.com/questions/19146056/document-evaluate-allways-returns-null-in-singlenodevalue-on-some-pages-sites

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!