diff --git a/src/crawlee/_utils/urls.py b/src/crawlee/_utils/urls.py
index 0f5409e74f..1f2a94415c 100644
--- a/src/crawlee/_utils/urls.py
+++ b/src/crawlee/_utils/urls.py
@@ -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`.
@@ -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
diff --git a/tests/unit/_utils/test_robots.py b/tests/unit/_utils/test_robots.py
index ce1779efe4..4ee87129a3 100644
--- a/tests/unit/_utils/test_robots.py
+++ b/tests/unit/_utils/test_robots.py
@@ -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/
diff --git a/tests/unit/_utils/test_sitemap.py b/tests/unit/_utils/test_sitemap.py
index 0d29f20d8f..9fd0167023 100644
--- a/tests/unit/_utils/test_sitemap.py
+++ b/tests/unit/_utils/test_sitemap.py
@@ -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}' for url in urls)
+ content = f'{entries}'
+ 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)
diff --git a/tests/unit/_utils/test_urls.py b/tests/unit/_utils/test_urls.py
index e4291c51e9..7f814d1e40 100644
--- a/tests/unit/_utils/test_urls.py
+++ b/tests/unit/_utils/test_urls.py
@@ -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'])
+@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')