Performing Google Search using Python code?

In this article, we will learn how to perform Google searches using Python code. This is particularly useful when working on projects that need to access web data or integrate search results into your application.

Prerequisites

  • Python installed on your system
  • Install the google module using pip ?
pip install google

Method 1: Getting Search Result URLs

This approach returns a list of URLs from Google search results that you can use programmatically ?

# Performing Google search and getting URLs
class GoogleSearch:
    def __init__(self, search_query):
        self.query = search_query
    
    def get_search_results(self):
        count = 0
        try:
            from googlesearch import search
        except ImportError:
            print("No module named 'google' found. Please install it using: pip install google")
            return
        
        print(f"Search results for: {self.query}")
        for url in search(query=self.query, tld='co.in', lang='en', num=10, stop=1, pause=2):
            count += 1
            print(f"{count}. {url}")

if __name__ == "__main__":
    searcher = GoogleSearch("Python tutorials")
    searcher.get_search_results()
Search results for: Python tutorials
1. https://www.tutorialspoint.com/python/
2. https://www.w3schools.com/python/
3. https://docs.python.org/3/tutorial/
4. https://realpython.com/
5. https://www.codecademy.com/learn/learn-python-3
6. https://www.learnpython.org/
7. https://automatetheboringstuff.com/
8. https://www.programiz.com/python-programming
9. https://pythonbasics.org/
10. https://www.geeksforgeeks.org/python-programming-language/

Method 2: Opening Search Results in Browser

This method directly opens the Google search page in your default web browser ?

import webbrowser
from urllib.parse import quote

def search_in_browser(query):
    # Encode the query for URL
    encoded_query = quote(query)
    search_url = f"https://google.com/search?q={encoded_query}"
    
    print(f"Opening search for: {query}")
    webbrowser.open(search_url)

# Example usage
search_query = "Python data science"
search_in_browser(search_query)
Opening search for: Python data science

Parameters Explanation

Parameter Description Example
query Search term "Python tutorials"
tld Top-level domain 'co.in' for India, 'com' for global
num Number of results per page 10
stop Number of pages to retrieve 1
pause Delay between requests (seconds) 2

Interactive Search Function

Here's a more user-friendly version that accepts input from the user ?

from googlesearch import search
import webbrowser

def interactive_search():
    print("Google Search Tool")
    print("1. Get URLs")
    print("2. Open in browser")
    
    choice = input("Choose option (1 or 2): ")
    query = input("Enter your search query: ")
    
    if choice == "1":
        print(f"\nTop 5 results for '{query}':")
        for i, url in enumerate(search(query, num=5, stop=1, pause=1), 1):
            print(f"{i}. {url}")
    
    elif choice == "2":
        search_url = f"https://google.com/search?q={query.replace(' ', '+')}"
        webbrowser.open(search_url)
        print(f"Opened search for '{query}' in browser")
    
    else:
        print("Invalid choice!")

# Uncomment to run interactively
# interactive_search()

Important Notes

  • Be mindful of Google's terms of service when scraping search results
  • Add delays between requests to avoid being blocked
  • The google module may require additional dependencies like beautifulsoup4
  • For production use, consider using official Google Search APIs

Conclusion

Python's google module provides an easy way to integrate Google search functionality into your applications. Use URL retrieval for data processing and browser opening for user interaction. Always respect rate limits and terms of service when automating searches.

Updated on: 2026-03-25T05:19:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements