#Importing the necessary module from the `googlesearch` library
from googlesearch import search
def perform_google_search(query, num_results=30, lang="en", country="US"):
try:
# Perform the Google search and iterate over the results
results = list(search(query, num_results=num_results, lang=lang, country=country))
# Print the URLs for each search result
print(f"\nTop {len(results)} URLs for '{query}':\n")
for index, url in enumerate(results, start=1):
print(f"{index}. {url}")
# Ask the user if they want to open any of the URLs
open_choice = input("\nDo you want to open any of the URLs? (y/n): ").lower()
if open_choice == 'y':
num_to_open = int(input(f"Enter the number of the URL to open (1 to {len(results)}, or 0 to skip): "))
if 0 < num_to_open <= len(results):
print(f"Opening URL: {results[num_to_open - 1]}")
# If you want to open the URL in the user's default web browser, use the following line:
# import webbrowser
# webbrowser.open(results[num_to_open - 1])
elif num_to_open != 0:
print("Invalid input. Not opening any URL.")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("Search completed successfully.")
if __name__ == "__main__":
print("Welcome to Google Search!")
print("This program allows you to perform a Google search and get the top URLs.")
print("You can specify the number of URLs to fetch and the language and country for targeted results.")
print("Leave the options blank and press Enter to use default values (30 results, English language, US country).")
# Prompt the user to enter their query
query = input("Enter Your Query:-> ").strip()
# Check if the user provided a query
if not query:
print("No query entered. Exiting the program.")
else:
# Ask for additional options
while True:
try:
num_results = int(input("Enter the number of URLs to fetch (default is 30): ") or 30)
if num_results > 0:
break
else:
print("Please enter a positive number.")
except ValueError:
print("Invalid input. Please enter a valid number.")
lang = input("Enter the language code (default is 'en' for English): ").strip() or "en"
country = input("Enter the country code (default is 'US'): ").strip() or "US"
# Call the function to perform the Google search
perform_google_search(query, num_results=num_results, lang=lang, country=country)