Perform Google Search using Python

Perform Google Search using Python

Introduction:

In the era of information technology, search engines have become an integral part of our daily lives. Google, being the most popular search engine, provides access to a vast amount of information with just a few keystrokes. In this blog, we will explore how to perform a Google search using Python and obtain the top 5 results for a user-specified query.

Python and GoogleSearch:

Python, with its extensive libraries and tools, allows us to interact with the web and retrieve data from various sources, including search engines. One such powerful library is "googlesearch-python," which enables us to perform Google searches programmatically.

Let's dive into the code:

from googlesearch import search


def get_user_query():
    return input("What do you want to search on Google? ")


def google_search(query):
    top_results = list(search(query, num_results=5))


    print(f"\nTop 5 results for '{query}':\n")
    for idx, result in enumerate(top_results, start=1):
        print(f"{idx}. {result}")


if __name__ == "__main__":
    user_query = get_user_query()
    google_search(user_query)

        

Explanation of the Code:

  1. Importing Required Libraries: To start, we import the search function from the googlesearch library.
  2. Defining Functions: We define two functions - get_user_query() and google_search(query).

  • get_user_query(): This function prompts the user to enter their search query and returns the input as a string.
  • google_search(query): The main function takes the user's query as input, performs the Google search using the search() function, and retrieves the top 5 results.

  1. Performing the Google Search: Within the google_search() function, we utilize the search() function from the googlesearch library. This function takes two arguments:

  • query: The user's search query that we obtained from get_user_query().
  • num_results: The number of search results to fetch. In our case, we fetch the top 5 results.

  1. Displaying the Results: After performing the search, we print the top 5 results along with their respective indices to make it easier for the user to identify each result.

Conclusion:

In this blog, we explored a simple Python script that enables us to perform a Google search and fetch the top 5 results based on a user-specified query. Python's vast ecosystem of libraries empowers developers to interact with the web in various ways, making it an ideal language for web scraping, data retrieval, and more.

With a little creativity and some additional programming, you can extend this simple Google search tool to suit your specific needs.



To view or add a comment, sign in

More articles by Ujjawal Kumar

Others also viewed

Explore content categories