Transforms JavaScript objects into Python data structures.
In web scraping, you sometimes need to transform Javascript objects embedded in HTML pages into valid Python dictionaries. chompjs is a library designed to do that as a more powerful replacement of standard json.loads:
parse_js_object - try reading first encountered JSON-like object. Raises ValueError on failure
parse_js_objects - returns a generator yielding all encountered JSON-like objects. Can be used to read JSON Lines. Does not raise on invalid input.
An example usage with scrapy:
import chompjs
import scrapy
class MySpider(scrapy.Spider):
# ...
def parse(self, response):
script_css = 'script:contains("__NEXT_DATA__")::text'
script_pattern = r'__NEXT_DATA__ = (.*);'
# warning: for some pages you need to pass replace_entities=True
# into re_first to have JSON escaped properly
script_text = response.css(script_css).re_first(script_pattern)
try:
json_data = chompjs.parse_js_object(script_text)
except ValueError:
self.log('Failed to extract data from {}'.format(response.url))
return
# work on json_data
loader_args and loader_kwargs arguments can be used to pass options to underlying loader function. For example for default json.loads you can pass down options such as strict or object_hook:
In web scraping data often is not present directly inside HTML, but instead provided as an embedded JavaScript object that is later used to initialize the page, for example:
The problem is that not all valid JavaScript objects are also valid JSONs. For example all those strings are valid JavaScript objects but not valid JSONs:
"{'a': 'b'}" is not a valid JSON because it uses ' character to quote
'{a: "b"}'is not a valid JSON because property name is not quoted at all
'{"a": [1, 2, 3,]}' is not a valid JSON because there is an extra , character at the end of the array
'{"a": .99}' is not a valid JSON because float value lacks a leading 0
As a result, json.loads fail to extract any of those:
Internally chompjs use a parser written in C to iterate over raw string, fixing its issues along the way. The final result is then passed down to standard library's json.loads, ensuring a high speed as compared to full-blown JavaScript parsers such as demjson.