web-search.py 2.4 KB

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