Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Drop invalid XML element attributes #462

Merged
merged 4 commits into from
Jan 2, 2024
Merged
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
5 changes: 4 additions & 1 deletion tests/unit_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,10 @@ def test_external():
teststring = f.read()
assert extract(teststring, no_fallback=True, include_tables=False) == ''
assert extract(teststring, no_fallback=False, include_tables=False) == ''

# invalid XML attributes: namespace colon in attribute key (issue #375). Those attributes should be stripped
bad_xml = 'Testing<ul style="" padding:1px; margin:15px""><b>Features:</b> <li>Saves the cost of two dedicated phone lines.</li> al station using Internet or cellular technology.</li> <li>Requires no change to the existing Fire Alarm Control Panel configuration. The IPGSM-4G connects directly to the primary and secondary telephone ports.</li>'
res = extract(bad_xml, output_format='xml')
assert "Features" in res

def test_images():
'''Test image extraction function'''
Expand Down
6 changes: 6 additions & 0 deletions trafilatura/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,12 @@ def sanitize_tree(tree):
preserve_space = elem.tag in SPACING_PROTECTED or parent_tag in SPACING_PROTECTED
trailing_space = elem.tag in FORMATTING_PROTECTED or parent_tag in FORMATTING_PROTECTED or preserve_space

# remove invalid attributes
for attribute in elem.attrib:
if ':' in attribute: # colon is reserved for namespaces in XML
if not elem.attrib[attribute] or attribute.split(':', 1)[0] not in tree.nsmap:
elem.attrib.pop(attribute)

if elem.text:
elem.text = sanitize(elem.text, preserve_space, trailing_space)
if elem.tail:
Expand Down
Loading