Python - Selenium - Autocomplete

By xngo on June 24, 2019

Selenium is able to select the autocomplete suggestions from Google search. Here is the code showing how.

#!/usr/bin/python3
 
import time
 
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
 
driver = webdriver.Chrome()
driver.get("https://www.google.com")
 
search_box = driver.find_element_by_name('q')  # Find search input box.
search_box.send_keys('selenium')               # Type in selenium.
time.sleep(1)
 
# Select the 3rd options from the autocomplete.
driver.switch_to_active_element()
 
search_box.send_keys(Keys.ARROW_DOWN)          # Press ARROW_DOWN key.
time.sleep(1)
search_box.send_keys(Keys.ARROW_DOWN)          # Press ARROW_DOWN key.
time.sleep(1)
search_box.send_keys(Keys.ARROW_DOWN)          # Press ARROW_DOWN key.
time.sleep(3)
 
# Search
search_box.send_keys(Keys.ENTER)

Here is a video showing the code above in action.

Video showing Selenium select autocomplete

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.