Creating the Web Searcher Module
Introduction: The Web Searcher Module
Welcome back! In the previous lesson, you learned how to use the DDGS library to search the web, fetch a single web page, and convert its content from HTML to Markdown. These are essential skills for building an automated research tool.
In this lesson, we will take the next step by creating a Web Searcher module. This module will allow you to search for a topic, fetch the top web pages, and convert their content to Markdown — all in one go. This is a key part of building a tool that can gather and process information from the web automatically.
By the end of this lesson, you will know how to combine searching, fetching, and converting web content into a single, reusable function. This will make your code cleaner and more powerful and prepare you for more advanced automation tasks later in the course.
Before we dive in, let’s quickly remind ourselves of the main tools we have used so far:
- DDGS: This library lets us perform web searches in Python and get results as structured data.
- httpx: This is a library for making HTTP requests, which we use to fetch web pages.
- html_to_markdown: This tool converts HTML content into Markdown, making it easier to read and process.
You have already seen how to use each of these tools separately. Now, we will see how to use them together to automate the process of searching for and retrieving useful web content.
Building the `search_and_fetch_markdown` Function
Now, let’s put everything we learned together into a single function. We want a function that:
- Takes a search query.
- Searches the web for the top results.
- Fetches each result’s web page.
- Converts the HTML to Markdown.
- Returns a list of dictionaries, each with the title, URL, and Markdown content.
Let’s build this step by step.
Step 1: Define the Function and Set Up the Search
- We import the needed libraries.
- The function takes a
query, and optionalmax_resultsandtimeout. - We create a
DDGSobject and perform the search. - We prepare an empty list to store the results.
