Making the Web Search Reliable and Safe
Introduction: The Need for Reliable and Safe Web Search
Welcome back! In the last lesson, you learned how to avoid common pitfalls in your web searcher, such as duplicate results and broken links. Now, we will take your skills a step further by making your web searcher more reliable and safe.
When you automate web content retrieval, you will often face problems like network errors, slow responses, or even accidentally processing the same page more than once. If you don’t handle these issues, your research tool might miss important information or waste time and resources.
In this lesson, you will learn how to:
- Automatically retry failed web requests,
- And use logging to monitor what happens during your web search.
By the end of this lesson, you will have a web searcher that is much more robust and ready for real-world use.
Retrying Failed Requests with Tenacity
When you fetch web pages, sometimes things go wrong. The website might be slow, your internet connection might drop, or the server might return an error. If you don’t handle these problems, your program could crash or miss important data.
To solve this, you can use the tenacity library. This library lets you automatically retry a function if it fails due to certain errors, such as timeouts or connection problems.
Let’s start by importing the necessary modules and setting up a simple retry mechanism.
Here’s what each import does:
tenacityprovides decorators and tools for retrying functions.httpxis the library we use to make HTTP requests.- The exception types (
TimeoutException,RequestError,HTTPStatusError) help us specify which errors should trigger a retry.
Now, let’s create a function that fetches a web page and automatically retries if it fails due to a network error or timeout.
Let’s break down what’s happening here:
- The
@retrydecorator tells Python to retry thefetch_pagefunction up to 3 times if it fails due to a timeout, connection error, or HTTP error. wait_exponentialmeans the wait time between retries will grow each time (2 seconds, then 4, then 8, up to 10 seconds).- Inside the function, we use
httpx.Clientto fetch the web page. If the request fails, the function will automatically retry.
Example Output:
If the first attempt fails due to a timeout, you might see:
If the third attempt succeeds, the function returns the page content. If all attempts fail, the error is raised.
