Last active
July 30, 2022 12:53
-
-
Save fearsum-fyz/77ed5595ca0ffdea2ad9b5520aa2f166 to your computer and use it in GitHub Desktop.
Make google searches programmatically in Python for free without the API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| from selenium import webdriver | |
| from selenium.webdriver.common.by import By | |
| from selenium.webdriver.common.keys import Keys | |
| from selenium.webdriver.support.ui import WebDriverWait | |
| from selenium.webdriver.support import expected_conditions as EC | |
| from chromedriver_autoinstaller import install | |
| has_chrome = input("Do you have the LATEST VERSION of chrome? (Y/N)\n") | |
| if has_chrome == "N": | |
| print("Please download and install the latest version of chrome from here and re-run.\nhttps://www.google.com/intl/en_in/chrome/") | |
| sys.exit() | |
| elif has_chrome != "Y": | |
| print("Invalid input. You were supposed to type either 'Y' or 'N' (without the single quotes). I'm too lazy to put this in a while loop, so re-run.") | |
| sys.exit() | |
| has_chromedriver = input("Do you have chromedriver for the latest version of chrome? [Y/N]\n") | |
| if has_chromedriver == "N": | |
| print("Download and re-run.\nhttps://chromedriver.chromium.org/downloads") | |
| sys.exit() | |
| business_name = input("What is the name of the business?\n") | |
| options = webdriver.ChromeOptions() | |
| options.add_argument("--headless") | |
| options.add_argument("--no-sandbox") | |
| options.add_argument("--disable-dev-shm-usage") | |
| driver = webdriver.Chrome(options = options) | |
| driver.get("http://www.google.com") | |
| search_bar = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, "q"))) | |
| search_bar.send_keys(business_name) | |
| search_bar.send_keys(Keys.ENTER) | |
| first_result = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "h3"))) | |
| first_result_link = first_result.find_element(by = By.XPATH, value = '..') | |
| print(first_result_link.get_attribute("href")) | |
| driver.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment