Skip to content

Commit 3a58843

Browse files
authored
fix(crawlers): Detect JSON served as text/html and handle empty responses in ParselCrawler (#2266)
### Description `ParselCrawler` detects a JSON body served as `text/html` as JSON again, so `context.selector.jmespath` works on it. HTML responses starting with an XML declaration are still parsed as HTML. An empty response body no longer fails the request. It's parsed as an empty HTML document. Follow-up to #2262 ### Testing - Added new regression tests
1 parent ccdb72c commit 3a58843

3 files changed

Lines changed: 52 additions & 18 deletions

File tree

‎src/crawlee/crawlers/_parsel/_parsel_parser.py‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,20 @@ def find_links(self, parsed_content: Selector, selector: str, attribute: str) ->
5050

5151
@staticmethod
5252
def _parse_body(body: bytes, content_type: str | None) -> Selector:
53-
media_type = (content_type or '').split(';')[0].strip().lower()
54-
# Other responses keep Parsel's own detection of JSON, XML and HTML.
55-
selector_type = 'html' if media_type in {'text/html', 'application/xhtml+xml'} else None
53+
# Parsel rejects an empty body, but reads empty text as an empty HTML document.
54+
if not body:
55+
return Selector(text='')
5656

5757
encoding = get_declared_html_encoding(body, content_type)
58-
if encoding is None:
58+
text = None if encoding is None else decode_html_body(body, encoding)
59+
60+
# Parsel detects a JSON object or array as JSON, and servers can send JSON as `text/html`.
61+
may_be_json = body.lstrip()[:1] in (b'{', b'[') if text is None else text.lstrip()[:1] in ('{', '[')
62+
63+
# Parsel reads a page starting with an XML declaration as XML, where CSS selectors miss XHTML elements.
64+
media_type = (content_type or '').split(';')[0].strip().lower()
65+
selector_type = 'html' if media_type in {'text/html', 'application/xhtml+xml'} and not may_be_json else None
66+
67+
if text is None:
5968
return Selector(body=body, type=selector_type)
60-
return Selector(text=decode_html_body(body, encoding), type=selector_type)
69+
return Selector(text=text, type=selector_type)

‎tests/unit/crawlers/_parsel/test_parsel_crawler.py‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import codecs
34
import sys
45
from typing import TYPE_CHECKING, Any
56
from unittest import mock
@@ -21,6 +22,7 @@
2122
_CZECH = 'Test dekódování znaků českého jazyka'
2223
_UKRAINIAN = 'Тест декодування символів української мови'
2324
_CHINESE = '中文字符解码测试'
25+
_XHTML = b'<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><body><a href="/next">Next</a></body></html>'
2426

2527

2628
async def test_basic(server_url: URL, http_client: HttpClient) -> None:
@@ -576,21 +578,35 @@ async def test_parse_decodes_page_encoding(texts: list[str], body: bytes, conten
576578

577579

578580
@pytest.mark.parametrize(
579-
('content_type', 'expected_type'),
581+
('body', 'content_type', 'expected_type'),
580582
[
581-
pytest.param('text/html', 'html', id='html'),
582-
pytest.param('application/xhtml+xml; charset=utf-8', 'html', id='xhtml'),
583-
pytest.param('application/xml', 'xml', id='xml'),
583+
pytest.param(_XHTML, 'text/html', 'html', id='xhtml-as-html'),
584+
pytest.param(_XHTML, 'application/xhtml+xml; charset=utf-8', 'html', id='xhtml-as-xhtml'),
585+
pytest.param(_XHTML, 'application/xml', 'xml', id='xhtml-as-xml'),
586+
pytest.param(b'{"hello": "world"}', 'text/html', 'json', id='json-as-html'),
587+
pytest.param(b'{"hello": "world"}', 'text/html; charset=utf-8', 'json', id='json-as-html-charset'),
588+
pytest.param(b' \n[1, 2]', 'text/html', 'json', id='json-after-whitespace'),
589+
pytest.param(b'\n{"hello": "world"}', 'text/html; charset=utf-8', 'json', id='json-after-whitespace-charset'),
590+
pytest.param(b'[<a href="/next">Next</a>]', 'text/html', 'html', id='bracket-not-json'),
591+
pytest.param(codecs.BOM_UTF8 + b'{"hello": "world"}', 'text/html', 'json', id='json-with-bom'),
592+
pytest.param(codecs.BOM_UTF8 + _XHTML, 'text/html', 'html', id='xhtml-with-bom'),
593+
pytest.param(_UKRAINIAN.encode('cp1251'), 'text/html', 'html', id='non-ascii-start'),
584594
],
585595
)
586-
async def test_parse_xml_declaration(content_type: str, expected_type: str) -> None:
587-
"""A page starting with an XML declaration is read as HTML unless the response is XML."""
588-
body = (
589-
b'<?xml version="1.0" encoding="UTF-8"?>'
590-
b'<html xmlns="http://www.w3.org/1999/xhtml"><body><a href="/next">Next</a></body></html>'
591-
)
596+
async def test_parse_selector_type(body: bytes, content_type: str, expected_type: str) -> None:
597+
"""An HTML response starting with an XML declaration is read as HTML, while JSON and XML keep their type."""
592598
response = mock.Mock(headers=HttpHeaders({'Content-Type': content_type}), read=mock.AsyncMock(return_value=body))
593599

594600
selector = await ParselParser().parse(response)
595601

596602
assert selector.type == expected_type
603+
604+
605+
async def test_parse_empty_body() -> None:
606+
"""An empty body is read as an empty HTML document."""
607+
response = mock.Mock(headers=HttpHeaders({'Content-Type': 'text/html'}), read=mock.AsyncMock(return_value=b''))
608+
609+
selector = await ParselParser().parse(response)
610+
611+
assert selector.type == 'html'
612+
assert selector.css('a').getall() == []

‎tests/unit/server.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -223,10 +223,19 @@ async def hello_world_json(_scope: dict[str, Any], _receive: Receive, send: Send
223223

224224
async def hello_world_xml(_scope: dict[str, Any], _receive: Receive, send: Send) -> None:
225225
"""Handle basic requests with a simple XML response."""
226-
await send_html_response(
227-
send,
228-
b"""<?xml version="1.0"?>
226+
await send(
227+
{
228+
'type': 'http.response.start',
229+
'status': 200,
230+
'headers': [[b'content-type', b'application/xml']],
231+
}
232+
)
233+
await send(
234+
{
235+
'type': 'http.response.body',
236+
'body': b"""<?xml version="1.0"?>
229237
<hello>world</hello>""",
238+
}
230239
)
231240

232241

0 commit comments

Comments
 (0)