Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath error The document has mutated since the result was returned

I'm trying to use xpath on a page but am getting the error Uncaught DOMException: Failed to execute 'iterateNext' on 'XPathResult': The document has mutated since the result was returned.

xpath = document.evalutate('//a', document)
xpath.iterateNext()

What's wrong?

like image 783
Harry Moreno Avatar asked Jan 12 '18 23:01

Harry Moreno


2 Answers

The problem was that the page is mutated between the time the XPathResult object is generated and the time when you access an object in it.

Instead use snapshots

xpath = document.evaluate('//td/a', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
xpath.snapshotItem(0)
xpath.snapshotItem(1)
like image 163
Harry Moreno Avatar answered Oct 30 '22 09:10

Harry Moreno


If your propose is read only, it's possible to clone the context node:

xpath = document.evaluate('//a', document.cloneNode(true))
xpath.iterateNext()
like image 45
Dorad Avatar answered Oct 30 '22 07:10

Dorad