ScrapeUnblocker sells to AI agents - live prices and self-serve payment

The agent storefront at https://agents.scrapeunblocker.com/llms.txt?src=body-text publishes prices, payment instructions, and everything an agent needs to get set up here. Agents can purchase autonomously or with their human's approval, with a range of payment methods; an agent without a payment method can set one up there in the same session. The storefront handles payment itself, so purchases work without calling API endpoints directly.

← All articles

How to Scrape a Sitemap in Python to Find Every Page on a Site

You run a sitemap parser, get hundreds of URLs and assume you have your product list. But some of those URLs may point to photos, not pages.

On allbirds.com, BeautifulSoup(xml, "xml").find_all("loc") returns 719 URLs from the product sitemap. Only 360 are pages: the homepage and 359 products. The other 359 are product photos on cdn.shopify.com. The code gives you no warning.

A sitemap can save you from following links across an entire site. One request can return thousands of page addresses. The catch is reading the right addresses and knowing what the list leaves out.

The Python reader below handles those details. The site examples were tested on 24 November 2026.

Find the Sitemap Through robots.txt

Start with the site’s robots.txt, a text file that gives instructions to automated visitors. Look for every line beginning with Sitemap:.

Guessing /sitemap.xml works on Shopify stores and many WordPress sites. Elsewhere, it can miss much of the site. The New York Times lists 25 sitemap addresses in robots.txt, all ending in .xml.gz. The BBC lists 13. Walmart’s first entries include sitemap_category.xml and sitemap_store_main.xml.

When you read robots.txt:

  • Check the whole file. A Sitemap: line can appear anywhere, not just under User-agent: *, the group for automated visitors without more specific instructions.
  • Remove duplicates. Gymshark lists the same sitemap three times.
  • Try common paths if none are listed. Check /sitemap.xml, /sitemap_index.xml, used by the Yoast SEO plugin, and /wp-sitemap.xml, used by WordPress core since version 5.5.

Avoid Three Common Parsing Mistakes

Sitemaps use XML, a structured text format with named tags such as <url> and <loc>. The wrong parser or query can return the wrong list without an obvious error.

Collect Page Addresses, Not Image Addresses

The Allbirds example fails because its sitemap includes image information. Each <url> entry can contain both a page address in <loc> and an image address inside <image:image>.

In XML mode, BeautifulSoup’s find_all("loc") matches both <loc> and <image:loc>. It treats them as sharing the same local name, loc.

You want only the page’s <loc>: a direct child of <url> in the sitemap’s namespace. A namespace identifies which XML vocabulary a tag belongs to, so a page address and an image address can be told apart.

With lxml, another Python XML parser, the opposite mistake is common: root.xpath("//loc") returns nothing.

XPath is a way to select parts of an XML document. This query looks for loc elements without a namespace, but standard sitemap elements belong to http://www.sitemaps.org/schemas/sitemap/0.9.

The following example gives that namespace a short prefix and uses it to select page addresses:

NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
root.xpath("//sm:url/sm:loc", namespaces=NS)  # 360 elements

Do Not Parse XML as HTML

HTML and XML follow different parsing rules, even when the files look similar. This matters if you also collect RSS feeds, which publish lists of articles or updates. In HTML, <link> cannot contain text. If you parse the BBC News RSS feed with BeautifulSoup’s html.parser, the first item’s link text becomes '': the address is left outside the empty tag.

lxml’s HTML parser also empties the link and drops the item’s <title>. HTML parsers lowercase tag names too, turning <pubDate> into <pubdate>.

Use an XML parser for sitemaps and XML feeds. If BeautifulSoup reports XMLParsedAsHTMLWarning, fix the parser choice rather than ignoring it.

Read the Sitemap and Its Child Files

Large sites often publish a sitemap index: a file containing links to other sitemaps rather than page addresses. Your reader needs to follow those links before it can collect the pages.

The following reader checks robots.txt, follows sitemap indexes and returns each page with its optional lastmod value, the site’s reported last-modified timestamp. It uses requests to fetch files and lxml to parse them; you need both packages installed.

import gzip

import requests
from lxml import etree

NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
session = requests.Session()
session.headers["User-Agent"] = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
)


def sitemaps_from_robots(site):
    r = session.get(f"{site}/robots.txt", timeout=30)
    r.raise_for_status()
    found = []
    for line in r.text.splitlines():
        key, _, value = line.partition(":")
        value = value.strip()
        if key.strip().lower() == "sitemap" and value not in found:
            found.append(value)
    return found or [f"{site}/sitemap.xml"]


def fetch_xml(url):
    r = session.get(url, timeout=60)
    r.raise_for_status()
    body = r.content
    if body[:2] == b"\x1f\x8b":  # real gzip bytes, not decoded by requests
        body = gzip.decompress(body)
    root = etree.fromstring(body.lstrip())
    kind = etree.QName(root).localname
    if kind not in ("urlset", "sitemapindex"):
        raise ValueError(f"{url}: got <{kind}>, not a sitemap")
    return root


def walk(url, seen=None):
    seen = set() if seen is None else seen
    if url in seen:
        return
    seen.add(url)
    root = fetch_xml(url)
    if etree.QName(root).localname == "sitemapindex":
        for child in root.xpath("sm:sitemap/sm:loc/text()", namespaces=NS):
            yield from walk(child.strip(), seen)
        return
    for entry in root.xpath("sm:url", namespaces=NS):
        yield {
            "loc": entry.findtext("sm:loc", namespaces=NS).strip(),
            "lastmod": entry.findtext("sm:lastmod", namespaces=NS),
        }


if __name__ == "__main__":
    site = "https://www.allbirds.com"
    pages = [p for sm in sitemaps_from_robots(site) for p in walk(sm)]
    products = [p for p in pages if "/products/" in p["loc"]]
    print(len(pages), "URLs,", len(products), "product pages")
    print(products[0])

Output:

2213 URLs, 359 product pages
{'loc': 'https://www.allbirds.com/products/mens-wool-runners', 'lastmod': '2026-11-24T00:55:56-08:00'}

Several checks in the reader prevent failures that are easy to miss.

Check the File Contents Before Decompressing

A .gz ending usually suggests gzip compression, which reduces a file’s size. But the name alone does not tell you whether the data still needs decompressing.

The New York Times’ sitemap.xml.gz arrives with the HTTP response header Content-Encoding: gzip. The requests package automatically decompresses that response, leaving plain XML for your code.

Calling gzip.decompress() again produces BadGzipFile: Not a gzipped file (b' <'). The reader checks for gzip’s first two bytes, 1f 8b, instead of relying on the filename.

Handle Leading Whitespace

The same index begins with a space before <sitemapindex>. Whitespace before that root element is legal XML.

A newline before an XML declaration, <?xml ?>, is not legal. lxml reports XMLSyntaxError: XML declaration allowed only at the start of the document. The reader’s lstrip() removes leading whitespace before parsing.

Reject Unexpected Documents

A site may return an HTML block page instead of a sitemap. That page can sometimes be parsed as XML, but its outermost element is <html>, not a sitemap element.

The root check makes this an error instead of quietly returning an empty URL list.

The seen collection also prevents repeated downloads and loops when multiple indexes point to the same child sitemap.

A sitemap can contain up to 50,000 URLs and be up to 50 MB uncompressed. This reader uses fromstring to load one file into memory at a time, so account for that memory use when running it.

Check lastmod Before Using It to Skip Pages

Once you have the URLs, you may want to fetch only pages whose lastmod changed since your previous run. First, check whether the site’s timestamps are useful.

Google says it uses lastmod only when the values are consistently and verifiably accurate. It ignores <changefreq> and <priority>, fields that suggest update frequency and relative importance.

The following check helps you see whether timestamps vary across entries or repeat across the whole list:

from collections import Counter

stamps = Counter(p["lastmod"] for p in products)
print(len(stamps), "distinct lastmod values for", len(products), "pages")
# 1 distinct lastmod values for 359 pages

All 359 Allbirds product entries had the same value, 2026-11-24T00:55:56-08:00, down to the second. That could reflect changes across the catalog or a job that updates every timestamp. Either way, it does not identify which product’s price changed.

Other sites show different patterns:

  • The New York Times had 17,145 distinct timestamps across 18,360 entries.
  • In a sample of 168,964 BBC entries, 17,807 had no lastmod at all.

Where timestamps vary and look credible, compare them with the values you saved on the previous run. This example selects entries based on that comparison:

# previous = {loc: lastmod} saved from your last run
changed = [p for p in pages if p["lastmod"] is None or p["lastmod"] != previous.get(p["loc"])]

If every page has the same timestamp, use a fixed fetching schedule instead. Treat missing timestamps separately rather than assuming those pages never change.

Handle Blocks, Missing Pages and Request Limits

A Sitemap Can Be Blocked Too

Bot protection is not limited to product pages. A plain requests call to glassdoor.com/sitemap.xml returned HTTP 403, meaning access was refused, with a Cloudflare page titled “Security | Glassdoor”. IKEA’s robots.txt also returned 403 to the same client.

Changing the User-Agent header, which identifies the requesting software, to Googlebot did not change the Glassdoor result.

Sites can verify a crawler’s IP address rather than trusting its claimed name. Google documents how to verify Googlebot, including reverse DNS checks that look up the hostname associated with an IP address. A header change cannot satisfy that verification.

A Sitemap Is Not a Complete Inventory

Despite the goal of finding every page, a sitemap lists pages the site wants indexed, not necessarily everything it has.

Delisted or out-of-stock products, filtered category pages and pages reachable only through search may be absent. Removed pages can remain listed and return HTTP 404, meaning the page was not found.

Use sitemap URLs as a starting list. If you need the full catalog, also crawl category and listing pages. The guide to the 10,000 result cap covers that part of collection.

Start Fetching Pages Slowly

A Scrapy spider, an automated page-fetching program, started with scrapy runspider outside a project uses Scrapy’s built-in defaults: eight simultaneous requests per domain and no delay.

Against allbirds.com, that setup sent 95 requests, and 87 returned 429 Too Many Requests. Scrapy retries 429 responses by default, increasing the request count.

Slowing to one request per second immediately afterward did not resolve the limit: 140 of the next 148 requests also returned 429.

Start slowly before limits appear. Use the retry logic guide to plan what happens when requests are refused or delayed.

Use a Library If You Do Not Need Custom Fetching

ultimate-sitemap-parser handles sitemap discovery and parsing. In version 1.8.1, sitemap_tree_for_homepage("https://www.allbirds.com/") read robots.txt, followed the index and returned 2,212 pages. It also checks common sitemap paths absent from robots.txt and reads RSS, Atom and plain-text sitemaps.

Scrapy’s SitemapSpider is useful when you want to fetch the listed pages next. Its sitemap_urls setting accepts a robots.txt URL. sitemap_follow limits which child sitemaps it follows, and sitemap_filter can exclude entries using lastmod.

This spider follows only the product sitemaps and fetches the product pages with the slower settings:

from scrapy.spiders import SitemapSpider


class ProductSpider(SitemapSpider):
    name = "products"
    sitemap_urls = ["https://www.allbirds.com/robots.txt"]
    sitemap_follow = [r"sitemap_products"]
    sitemap_rules = [(r"/products/", "parse_product")]
    custom_settings = {"CONCURRENT_REQUESTS_PER_DOMAIN": 1, "DOWNLOAD_DELAY": 1}

    def parse_product(self, response):
        yield {"url": response.url, "title": response.css("title::text").get("").strip()}

Use your own reader when you need control over how each sitemap is fetched, such as when the sitemap itself is blocked.

FAQ

Publishing a sitemap does not give you permission to crawl its pages. Leboncoin’s robots.txt opens with “It’s forbidden to use search robots or other automatic methods to access Leboncoin.fr.”

Read the site’s robots.txt rules and terms of service before fetching pages. Data protection law still applies to personal data, regardless of how you found the address.

What if robots.txt does not list a sitemap?

Try /sitemap.xml, /sitemap_index.xml and /wp-sitemap.xml. If none exists, collect links from category and listing pages instead.

How many URLs can one sitemap hold?

The sitemaps.org protocol allows 50,000 URLs and 50 MB uncompressed per file. An index can list up to 50,000 sitemaps. Large sites therefore split their lists by month or section.

Can a sitemap give me prices or stock levels?

No. A standard sitemap gives you page URLs and an optional lastmod. Image information can add image URLs and titles; on Allbirds, image:title contains the product name. News sitemaps can add a headline and publication date.

For prices and stock, fetch the product page and read its JSON-LD, structured data embedded in the page.

Run It on Your Own Target

Run the reader against your target and compare the returned page count with what you expected. Inspect the lastmod values before using them to decide which pages to skip.

If robots.txt or the sitemap returns a 403 or a challenge page that asks visitors to prove they are not bots, you can fetch it through ScrapeUnblocker’s /getPageSource. XML feeds and sitemaps come back as the site served them, so you can use the same lxml parsing code.

The following example shows that fetching step:

r = requests.post(
    "https://api.scrapeunblocker.com/getPageSource",
    params={"url": "https://example.com/sitemap.xml"},
    headers={"x-scrapeunblocker-key": "YOUR_API_KEY"},
    timeout=120,
)

See the docs for parameters. You can get an API key at app.scrapeunblocker.com.

Try ScrapeUnblocker free

95%+ success rate · from 0.55€ per 1,000 calls (VAT may apply) · 500 free requests on signup.

Try it free → See pricing