web-search.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #Web Search
  2. #Developed by : PythonCoder8
  3. #Requires Pip installation : pip install google
  4. #Description : Search web for query and retrieve a selected amount of URLs
  5. #Python version : Major = 3
  6. #Only tested with 3.8.5
  7. #########################################################################################
  8. #Import required libraries
  9. from time import time
  10. from googlesearch import search
  11. import sys
  12. import webbrowser
  13. search_query = input('What do you want to search for on the web?: ')
  14. result_num = input('How many results do you want to retrieve from the web?: ')
  15. #Verify user input
  16. try:
  17. int_result_num = int(result_num)
  18. except:
  19. sys.exit('The number of results you wanted to retrieve was not a number. Exiting program...')
  20. #Display web results
  21. print('The top %d results from the web are:' %(int_result_num))
  22. start = time()
  23. for url in search(search_query, tld='com', stop=int_result_num):
  24. print(url)
  25. end = time()
  26. print('Found %d results from the web in %s' %(int_result_num, end - start) + ' seconds.')
  27. #Ask user if they want to open the links in the web browser with validation
  28. open_in_browser = input('Do you want to open the given URLs in your web browser (Y/N)? ')
  29. if open_in_browser.upper() == 'Y':
  30. for url in search(search_query, tld='com', stop=int_result_num):
  31. webbrowser.open(url)
  32. elif open_in_browser.upper() == 'N':
  33. sys.exit('Ok! Bye!')
  34. else:
  35. while open_in_browser.upper() != 'Y' and open_in_browser.upper() != 'N':
  36. open_in_browser = input('Invalid response! Do you want to open the given URLs in your web browser (Y/N)? ')
  37. if open_in_browser.upper() == 'Y':
  38. for url in search(search_query, tld='com', stop=int_result_num):
  39. webbrowser.open(url)
  40. elif open_in_browser.upper() == 'N':
  41. sys.exit('Ok! Bye!')