sax-jsvspyquery
sax-js is a streaming XML parser for Node.js that is built on top of the sax C library. It is designed to be fast, low-memory, and easy to use. It is commonly used for parsing large XML files, as it allows you to process the XML data incrementally, rather than loading the entire file into memory at once.
sax-js is a low-level html tree parser and does not provide html query capabilities (like CSS selectors) though it can be useful in HTML tree parsing and serialization.
PyQuery is a Python library for working with XML and HTML documents. It is similar to BeautifulSoup and is often used as a drop-in replacement for it.
PyQuery is inspired by javascript's jQuery and uses similar API allowing selecting of HTML nodes through CSS selectors. This makes it easy for developers who are already familiar with jQuery to use PyQuery in Python.
Unlike jQuery, PyQuery doesn't support XPath selectors and relies entirely on CSS selectors though offers similar HTML parsing features like selection of HTML elements, their attributes and text as well as html tree modification.
PyQuery also comes with a http client (through requests
) so it can load and parse web URLs by itself.
Highlights
Example Use
const fs = require("fs");
const sax = require("sax");
const xmlStream = fs.createReadStream("example.xml");
const saxParser = sax.createStream(true, {});
saxParser.on("opentag", function(node) {
console.log(`<${node.name}>`);
});
saxParser.on("closetag", function(nodeName) {
console.log(`</${nodeName}>`);
});
saxParser.on("text", function(text) {
console.log(text);
});
xmlStream.pipe(saxParser);
from pyquery import PyQuery as pq
# this is our HTML page:
html = """
<head>
<title>Hello World!</title>
</head>
<body>
<div id="product">
<h1>Product Title</h1>
<p>paragraph 1</p>
<p>paragraph2</p>
<span class="price">$10</span>
</div>
</body>
"""
doc = pq(html)
# we can use CSS selectors:
print(doc('#product .price').text())
"$10"
# it's also possible to modify HTML tree in various ways:
# insert text into selected element:
print(doc('h1').append('<span>discounted</span>'))
"<h1>Product Title<span>discounted</span></h1>"
# or remove elements
doc('p').remove()
print(doc('#product').html())
"""
<h1>Product Title<span>discounted</span></h1>
<span class="price">$10</span>
"""
# pyquery can also retrieve web documents using requests:
doc = pq(url='http://httpbin.org/html', headers={"User-Agent": "webscraping.fyi"})
print(doc('h1').html())