web-search.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. width = 40
  14. titletxt = 'Web-Search'
  15. title = titletxt.center(width)
  16. print(title)
  17. search_query = input('\nWhat do you want to search for on the web?: ')
  18. result_num = input('How many results do you want to retrieve from the web?: ')
  19. #Verify user input
  20. try:
  21. int_result_num = int(result_num)
  22. except:
  23. sys.exit('The number of results you wanted to retrieve was not a number. Exiting program...')
  24. #Display web results
  25. print('The top %d results from the web are:' %(int_result_num))
  26. start = time()
  27. for url in search(search_query, tld='com', stop=int_result_num):
  28. print(url + " - %s" %(url.split('/')[2]))
  29. end = time()
  30. print('Found %d results from the web in %s' %(int_result_num, end - start) + ' seconds.')
  31. #Delete time variables to clear RAM
  32. del start
  33. del end
  34. #Ask user if they want to open the links in the web browser with validation
  35. open_in_browser = input('Do you want to open the given URLs in your web browser (Y/N)? ')
  36. if open_in_browser.upper() == 'Y':
  37. for url in search(search_query, tld='com', stop=int_result_num):
  38. webbrowser.open(url)
  39. elif open_in_browser.upper() == 'N':
  40. sys.exit('Ok! Bye!')
  41. else:
  42. while open_in_browser.upper() != 'Y' and open_in_browser.upper() != 'N':
  43. open_in_browser = input('Invalid response! Do you want to open the given URLs in your web browser (Y/N)? ')
  44. if open_in_browser.upper() == 'Y':
  45. for url in search(search_query, tld='com', stop=int_result_num):
  46. webbrowser.open(url)
  47. elif open_in_browser.upper() == 'N':
  48. sys.exit('Ok! Bye!')