Skip to content
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
15 changes: 11 additions & 4 deletions src/crawlee/_utils/sitemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@ async def _process_sitemap_item(
return

# Add to processing queue
visited_sitemap_urls.add(sitemap_url)
sources.append(SitemapSource(type='url', url=sitemap_url, depth=depth + 1))

# Output the nested sitemap reference if requested
Expand Down Expand Up @@ -618,9 +619,17 @@ async def parse_sitemap(
timeout = options.get('timeout', timedelta(seconds=30))
enqueue_strategy = options.get('enqueue_strategy', 'same-hostname')

# Setup working state
sources = list(initial_sources)
# Setup working state. Sitemap URLs are marked as visited when they are queued, so a sitemap listed several times
# is queued and fetched once. The queue is breadth-first, so the queued copy is the shallowest one.
visited_sitemap_urls: set[str] = set()
sources: list[SitemapSource] = []
for initial_source in initial_sources:
if initial_source['type'] == 'url' and 'url' in initial_source:
if initial_source['url'] in visited_sitemap_urls:
continue
visited_sitemap_urls.add(initial_source['url'])
sources.append(initial_source)

successful_sources = 0
source_errors: list[Exception] = []

Expand Down Expand Up @@ -649,11 +658,9 @@ async def parse_sitemap(
successful_sources += 1

elif source['type'] == 'url' and 'url' in source:
# Add to visited set before processing to avoid duplicates
if http_client is None:
raise RuntimeError('HttpClient must be provided for URL-based sitemap sources.')

visited_sitemap_urls.add(source['url'])
parsed_ok: list[bool] = []

try:
Expand Down
48 changes: 48 additions & 0 deletions tests/unit/_utils/test_sitemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from crawlee._utils.sitemap import (
DEFAULT_MAX_DEPTH,
NestedSitemap,
ParseSitemapOptions,
Sitemap,
SitemapSource,
Expand Down Expand Up @@ -478,6 +479,53 @@ def body_for_url(url: str) -> bytes:
assert len(fetched) == DEFAULT_MAX_DEPTH + 1


async def test_duplicate_nested_sitemaps_fetched_once() -> None:
"""A nested sitemap listed several times, at several levels, is fetched only once."""
children = {'sitemap-a.xml': 'sitemap-b.xml', 'sitemap-b.xml': 'sitemap-c.xml'}

def body_for_url(url: str) -> bytes:
child = children.get(url.removeprefix(DEFAULT_URL))
if child is None:
return f'<urlset><url><loc>{DEFAULT_URL}page</loc></url></urlset>'.encode()
entry = f'<sitemap><loc>{DEFAULT_URL}{child}</loc></sitemap>'
return f'<sitemapindex>{entry * 5}</sitemapindex>'.encode()

client, fetched = _make_stream_client(body_for_url)
items = [item async for item in parse_sitemap([{'type': 'url', 'url': f'{DEFAULT_URL}sitemap-a.xml'}], client)]

assert fetched == [f'{DEFAULT_URL}sitemap-a.xml', f'{DEFAULT_URL}sitemap-b.xml', f'{DEFAULT_URL}sitemap-c.xml']
assert [item.loc for item in items] == [f'{DEFAULT_URL}page']


async def test_duplicate_nested_sitemap_emitted_once() -> None:
"""A nested sitemap listed several times is emitted as a `NestedSitemap` only once."""
index_url = f'{DEFAULT_URL}sitemap-index.xml'
child_url = f'{DEFAULT_URL}sitemap-child.xml'

def body_for_url(url: str) -> bytes:
if url == child_url:
return f'<urlset><url><loc>{DEFAULT_URL}page</loc></url></urlset>'.encode()
entry = f'<sitemap><loc>{child_url}</loc></sitemap>'
return f'<sitemapindex>{entry * 5}</sitemapindex>'.encode()

client, _ = _make_stream_client(body_for_url)
options = ParseSitemapOptions(emit_nested_sitemaps=True)
items = [item async for item in parse_sitemap([{'type': 'url', 'url': index_url}], client, options=options)]

assert [item.loc for item in items if isinstance(item, NestedSitemap)] == [child_url]


async def test_duplicate_initial_sources_fetched_once() -> None:
"""A sitemap URL given several times in the initial sources is fetched only once."""
sitemap_url = f'{DEFAULT_URL}sitemap.xml'
client, fetched = _make_stream_client(lambda _url: get_basic_sitemap().encode())
sources: list[SitemapSource] = [{'type': 'url', 'url': sitemap_url}, {'type': 'url', 'url': sitemap_url}]
items = [item async for item in parse_sitemap(sources, client)]

assert fetched == [sitemap_url]
assert len(items) == len(get_basic_results())


async def test_parse_sitemap_with_partial_options() -> None:
"""Test that missing keys in partial `ParseSitemapOptions` fall back to defaults."""
options = ParseSitemapOptions(timeout=timedelta(seconds=10))
Expand Down
Loading