Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Challenge: Async Web Scraper with Rate Limiting | Advanced Control and Debugging
Python Asyncio in Depth
Секція 4. Розділ 3
single

single

Challenge: Async Web Scraper with Rate Limiting

Свайпніть щоб показати меню

You are building a production-ready async data pipeline that fetches posts and their comments from jsonplaceholder.typicode.com. The pipeline must handle concurrency, apply rate limiting, enforce timeouts, and gracefully recover from individual failures.

The following endpoints are available:

  • https://jsonplaceholder.typicode.com/posts/{post_id} – returns a post object with title and userId fields;
  • https://jsonplaceholder.typicode.com/comments?postId={post_id} – returns a list of comments for a given post.
Завдання

Проведіть, щоб почати кодувати

  1. Define an async function fetch_post(client, semaphore, post_id) that:
    • uses the provided semaphore to limit concurrency;
    • fetches the post with a 4.0 second timeout using asyncio.wait_for();
    • returns a dict with keys post_id, title, and user_id;
    • returns None on any exception.
  2. Define an async function fetch_comment_count(client, semaphore, post_id) that:
    • uses the provided semaphore to limit concurrency;
    • fetches the comments list with a 4.0 second timeout;
    • returns the number of comments as an integer;
    • returns 0 on any exception.
  3. Define an async function build_report(client, semaphore, post_id) that:
    • calls fetch_post() and fetch_comment_count() concurrently using asyncio.gather();
    • returns None if fetch_post() returned None;
    • otherwise returns a formatted string: "[User {user_id}] {title} – {comment_count} comments".
  4. Define an async function main() that:
    • creates an asyncio.Semaphore with a limit of 5;
    • builds reports for post IDs 1 through 10 concurrently using asyncio.gather();
    • prints each non-None result on a separate line.
  5. Run main() using asyncio.run().

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 3
single

single

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

some-alt