Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion extruct/_extruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def extract(
processors.append(
(
"json-ld",
JsonLdExtractor().extract_items,
JsonLdExtractor(errors=errors).extract_items,
tree,
)
)
Expand Down
26 changes: 19 additions & 7 deletions extruct/jsonld.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
"""

import json
import logging
import re

import jstyleson
import lxml.etree

from extruct.utils import parse_html

logger = logging.getLogger(__name__)
HTML_OR_JS_COMMENTLINE = re.compile(r"^\s*(//.*|<!--.*-->)")


Expand All @@ -19,18 +21,28 @@ class JsonLdExtractor:
'descendant-or-self::script[@type="application/ld+json"]'
)

def __init__(self, errors="strict"):
self.errors = errors

def extract(self, htmlstring, base_url=None, encoding="UTF-8"):
tree = parse_html(htmlstring, encoding=encoding)
return self.extract_items(tree, base_url=base_url)

def extract_items(self, document, base_url=None):
return [
item
for items in map(self._extract_items, self._xp_jsonld(document)) # type: ignore[arg-type]
if items
for item in items
if item
]
items = []
for node in self._xp_jsonld(document): # type: ignore[arg-type]
try:
for item in self._extract_items(node) or ():
if item:
items.append(item)
except ValueError as e:
if self.errors == "strict":
raise
if self.errors == "log":
logger.exception(
"Failed to extract json-ld script, raises {}".format(e)
)
return items

def _extract_items(self, node):
script = node.xpath("string()").strip()
Expand Down
21 changes: 21 additions & 0 deletions tests/test_extruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,24 @@ def test_errors(self):
# ignore exceptions
data = extruct.extract(body, errors="log")
assert data == {}

def test_errors_ignore_keeps_valid_jsonld_siblings(self):
body = (
"<html><head>"
'<script type="application/ld+json">'
'{"@type":"Person","name":"Ada"}'
"</script>"
'<script type="application/ld+json">{not-json}</script>'
"</head></html>"
)
expected = {"json-ld": [{"@type": "Person", "name": "Ada"}]}
data = extruct.extract(body, errors="ignore", syntaxes=["json-ld"])
self.assertEqual(data, expected)

with self.assertLogs("extruct.jsonld", level="ERROR") as cm:
data = extruct.extract(body, errors="log", syntaxes=["json-ld"])
self.assertEqual(data, expected)
self.assertTrue(any("json-ld script" in line for line in cm.output))

with self.assertRaises(ValueError):
extruct.extract(body, errors="strict", syntaxes=["json-ld"])
26 changes: 26 additions & 0 deletions tests/test_jsonld.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,29 @@ def test_empty_jsonld_script(self):
body = '<script type="application/ld+json"> \n\n </script>'
data = jsonlde.extract(body)
self.assertEqual(data, [])

def test_malformed_sibling_raises_by_default(self):
jsonlde = JsonLdExtractor()
body = (
"<html><head>"
'<script type="application/ld+json">'
'{"@type":"Person","name":"Ada"}'
"</script>"
'<script type="application/ld+json">{not-json}</script>'
"</head></html>"
)
with self.assertRaises(ValueError):
jsonlde.extract(body)

def test_malformed_sibling_skipped_when_ignoring(self):
body = (
"<html><head>"
'<script type="application/ld+json">'
'{"@type":"Person","name":"Ada"}'
"</script>"
'<script type="application/ld+json">{not-json}</script>'
"</head></html>"
)
data = JsonLdExtractor(errors="ignore").extract(body)
self.assertEqual(data, [{"@type": "Person", "name": "Ada"}])