Using Google XPath implementation with jsdom - jsdom/jsdom GitHub Wiki
As of May 2016, jsdom XPath implementation is a subject to rewrite. If need be, users can use Google XPath implementation with jsdom in several ways.
- By injecting the browser version of wgxpath (
wgxpath.install.js
):
require('jsdom').env({
url: 'https://www.w3.org/TR/xpath/',
scripts: [require('path').join(__dirname, 'wgxpath.install.js')],
// or from Net: [`https://github.com/google/wicked-good-xpath/releases/download/1.3.0/wgxpath.install.js`],
done: (err, window) => {
window.wgxpath.install(window, true);
console.log(window.document.evaluate('.//title', window.document.documentElement,
null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent);
}
});
- By using Node.js version of wgxpath (
wgxpath.install-node.js
) as a module:
const wgxpath = require('./wgxpath.install-node.js');
require('jsdom').env({
url: 'https://www.w3.org/TR/xpath/',
done: (err, window) => {
wgxpath.install(window, true);
console.log(window.document.evaluate('.//title', window.document.documentElement,
null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent);
}
});
You can also install the NPM version.
In both cases we use undocumented second argument of wgxpath.install()
(see comments here) to redefine XPath methods and properties forcibly.
As for now, Google XPath is faster than jsdom XPath and implements more features (e.g. namespaces).