I'm into some web scraping with Node.js. I'd like to use XPath as I can generate it semi-automatically with several sorts of GUI. The problem is that I cannot find a way to do this effectively.
jsdom
is extremely slow. It's parsing 500KiB file in a minute or so with full CPU load and a heavy memory footprint.- Popular libraries for HTML parsing (e.g.
cheerio
) neither support XPath, nor expose W3C-compliant DOM. - Effective HTML parsing is, obviously, implemented in WebKit, so using
phantom
orcasper
would be an option, but those require to be running in a special way, not justnode <script>
. I cannot rely on the risk implied by this change. For example, it's much more difficult to find how to runnode-inspector
withphantom
. Spooky
is an option, but it's buggy enough, so that it didn't run at all on my machine.
What's the right way to parse an HTML page with XPath then?
I think Osmosis is what you're looking for.
Here's an example:
Libxmljs is currently the fastest implementation (something like a benchmark) since it's only bindings to the LibXML C-library which supports XPath 1.0 queries:
However, you need to sanitize your HTML first and convert it to proper XML. For that you could either use the HTMLTidy command line utility (
tidy -q -asxml input.html
), or if you want it to keep node-only, something like xmlserializer should do the trick.You can do so in several steps.
parse5
. The bad part is that the result is not DOM. Though it's fast enough and W3C-compiant.xmlserializer
that accepts DOM-like structures ofparse5
as input.xmldom
. Now you finally have that DOM.xpath
library builds uponxmldom
, allowing you to run XPath queries. Be aware that XHTML has its own namespace, and queries like//a
won't work.Finally you get something like this.
There might be never a right way to parse HTML pages. A very first review on web scraping and crawling shows me that Scrapy can be a good candidate for your need. It accepts both CSS and XPath selectors. In the realm of Node.js, we have a pretty new module node-osmosis. This module is built upon libxmljs so that it is supposed to support both CSS and XPath although I did not find any example using XPath.
I have just started using
npm install htmlstrip-native
which uses a native implementation to parse and extract the relevant html parts. It is claiming to be 50 times faster than the pure js implementation (I have not verified that claim).Depending on your needs you can use html-strip directly, or lift the code and bindings to make you own C++ used internally in htmlstrip-native
If you want to use xpath, then use the wrapper already avaialble here; https://www.npmjs.org/package/xpath