Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.10 — Collecting Web Data Responsibly
Python · Example 2 of 5

Scrape a table across pages, clean it, and cache it

The second call to scrape() fetches nothing: both pages come from the cache, as the list of network calls shows.

Web scraping means fetching web pages with a program and pulling data out of them. Use an official API when one exists, read the site's robots.txt and terms, identify your program, go slowly, cache what you fetch, handle personal data with care, and parse with a real HTML parser.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Using RobotFileParser.parse with the lines User-agent: * and Disallow: /admin/, print whether /admin/users and /news may be fetched by MyBot.

02

Write parse_links(html, base) that returns the full addresses of all links with an href in a page, using BeautifulSoup and urljoin. Test it on <a href='/a'>A</a><a href='https://other.example/b'>B</a><a>none</a> with base https://site.example/.

03

Write a fetch_all(client, first_path, max_pages) that follows an a.next link (page 1 links to page 2, page 2 has no link) using a MockTransport and returns how many pages it fetched.

Explain it without notes

01

Before writing a scraper, what should you check, and why?

02

What are robots.txt and the User-Agent header for, and how do you read robots.txt in Python?

03

How do you make a scraper polite? Name at least five behaviours.

04

How do you handle pagination safely, and what can go wrong with relative links?

05

What are the privacy and legal concerns when collecting web data, especially for an AI dataset?

Scrape a table across pages, clean it, and cache it
Sign in to run this example in your browser.

Expected output

{'title': 'Learning Python', 'price': 450.5, 'url': 'https://shop.example/book/1'}
{'title': 'Data at Work', 'price': 620.0, 'url': 'https://shop.example/book/2'}
{'title': 'Clean Code', 'price': 1299.0, 'url': 'https://shop.example/book/3'}
network calls: ['/catalog?page=1', '/catalog?page=2']