web-search.py 2.3 KB

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