You can download this code by clicking the button below.
This code is now available for download.
This function uses the selenium library to open the Google website, search for results based on the provided keyword, and click on the first search result link. Finally, it closes the browser.
Technology Stack : selenium, Chrome WebDriver, By, Keys, WebDriverWait, expected_conditions
Code Type : The type of code
Code Difficulty : Intermediate
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
def search_website_by_keyword(arg1, arg2):
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a website
driver.get("https://www.google.com")
# Find the search box and enter a keyword
search_box = driver.find_element(By.NAME, "q")
search_box.send_keys(arg1)
search_box.send_keys(Keys.RETURN)
# Wait for the results to load and click on the first link
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "h3"))
)
first_link = driver.find_element(By.CSS_SELECTOR, "h3")
first_link.click()
# Close the browser
driver.quit()