Skip to content
Open
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
11 changes: 8 additions & 3 deletions src/crawlee/_utils/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ def filter_url(
) -> tuple[bool, str | None]:
"""Check whether `target` is eligible to be enqueued under `strategy` relative to `origin`.

Combines the two checks every enqueue site needs: the URL must use a supported scheme
(`http` or `https`), and it must match `strategy` relative to `origin`. Callers that need to
Combines the checks every enqueue site needs: the URL must be parsable, it must use a supported
scheme (`http` or `https`), and it must match `strategy` relative to `origin`. Callers that need to
distinguish a scheme rejection from a strategy mismatch (for different log levels or dedup)
can compare the returned reason against `UNSUPPORTED_SCHEME_MESSAGE`.

Expand All @@ -98,7 +98,12 @@ def filter_url(
`(True, None)` if `target` is eligible. Otherwise `(False, reason)` where `reason` is
a human-readable rejection message suitable for log output.
"""
target_url = _to_url(target)
try:
target_url = _to_url(target)
# Reading the host decodes an IDNA host such as `xn--a.com`, which raises for an invalid one.
_ = target_url.host
except ValueError as error:
return False, f'cannot be parsed ({error})'

if not _is_supported_url_scheme(target_url):
return False, UNSUPPORTED_SCHEME_MESSAGE
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/_utils/test_robots.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,21 @@ async def test_get_sitemaps_with_strategy_all_returns_cross_host() -> None:
}


async def test_get_sitemaps_skips_unparsable_url() -> None:
"""A `Sitemap:` directive with a URL that cannot be parsed does not affect the other directives."""
content = (
'User-agent: *\n'
'Sitemap: http://example.com/sitemap_1.xml\n'
'Sitemap: http://example.com:99999/sitemap.xml\n'
'Sitemap: http://example.com/sitemap_2.xml\n'
)
robots = await RobotsTxtFile.from_content('http://example.com/robots.txt', content)
assert robots.get_sitemaps(enqueue_strategy='same-hostname') == [
'http://example.com/sitemap_1.xml',
'http://example.com/sitemap_2.xml',
]


async def test_parse_from_content() -> None:
content = """User-agent: *
Disallow: *deny_all/
Expand Down
21 changes: 21 additions & 0 deletions tests/unit/_utils/test_sitemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,27 @@ async def test_malformed_sitemap_keeps_urls() -> None:
assert sitemap.urls == [f'{DEFAULT_URL}first', f'{DEFAULT_URL}second']


@pytest.mark.parametrize(
'unparsable_url',
[
pytest.param('http://not-exists.com:99999/page', id='port_out_of_range'),
pytest.param('http://[::1', id='unclosed_ipv6_bracket'),
pytest.param('http://xn--a.com/', id='invalid_idna_host'),
],
)
async def test_unparsable_url_does_not_drop_rest_of_sitemap(unparsable_url: str) -> None:
"""A URL that cannot be parsed is skipped, and the sitemap is fetched once with all its other URLs kept."""
urls = ['http://not-exists.com/a', unparsable_url, 'http://not-exists.com/b']
entries = ''.join(f'<url><loc>{url}</loc></url>' for url in urls)
content = f'<?xml version="1.0" encoding="UTF-8"?><urlset>{entries}</urlset>'
client, fetched = _make_stream_client(lambda _url: content.encode())

sitemap = await Sitemap.load('http://not-exists.com/sitemap.xml', client)

assert sitemap.urls == ['http://not-exists.com/a', 'http://not-exists.com/b']
assert fetched == ['http://not-exists.com/sitemap.xml']


async def test_sitemap_fetch_retries_on_transient_error(monkeypatch: pytest.MonkeyPatch) -> None:
"""Transient fetch errors are retried up to `sitemap_retries` times before giving up."""
monkeypatch.setattr('crawlee._utils.sitemap.SITEMAP_RETRY_DELAY', 0)
Expand Down
17 changes: 17 additions & 0 deletions tests/unit/_utils/test_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,20 @@ def test_filter_url_same_domain(origin: str, target: str, *, expected: bool) ->
"""`same-domain` compares registrable domains, or host and port for hosts without one."""
ok, _ = filter_url(target=target, strategy='same-domain', origin=origin)
assert ok is expected


@pytest.mark.parametrize('strategy', ['all', 'same-hostname', 'same-domain', 'same-origin'])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you wrap these cases in pytest.param(..., id=...) too?

@pytest.mark.parametrize(
'target',
[
pytest.param('http://example.com:99999/', id='port_out_of_range'),
pytest.param('http://[::1', id='unclosed_ipv6_bracket'),
pytest.param('http://xn--a.com/', id='invalid_idna_host'),
],
)
def test_filter_url_rejects_unparsable_target(strategy: EnqueueStrategy, target: str) -> None:
"""A target URL that cannot be parsed is rejected with a reason under every strategy."""
ok, reason = filter_url(target=target, strategy=strategy, origin='http://example.com/')
assert ok is False
assert reason is not None
assert reason.startswith('cannot be parsed')