web-search.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 + " - %s" %(url.split('/')[2]))
  25. end = time()
  26. print('Found %d results from the web in %s' %(int_result_num, end - start) + ' seconds.')
  27. #Delete time variables to clear RAM
  28. del start
  29. del end
  30. #Ask user if they want to open the links in the web browser with validation
  31. open_in_browser = input('Do you want to open the given URLs in your web browser (Y/N)? ')
  32. if open_in_browser.upper() == 'Y':
  33. for url in search(search_query, tld='com', stop=int_result_num):
  34. webbrowser.open(url)
  35. elif open_in_browser.upper() == 'N':
  36. sys.exit('Ok! Bye!')
  37. else:
  38. while open_in_browser.upper() != 'Y' and open_in_browser.upper() != 'N':
  39. open_in_browser = input('Invalid response! 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!')