John Smith
John Smith

Reputation: 103

Python/Selenium How to select first option of autocomplete searchbar

I am trying to enter a keyword into a searchbar of this site and select the first autocomplete option that comes up. If I were to do this manually I would type in "remote" in the search bar and press the downkey and press enter which I have tried to replicate in my code below, but instead it seems to be skipping the downkey part and not selecting the first autocomplete option and going to the search results page instead of this page which is the first autocomplete option.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("https://confluence.eits.uga.edu/dashboard.action")

elem = driver.find_element_by_id("quick-search-query")
elem.send_keys("remote")
elem.send_keys(Keys.ARROW_DOWN)
elem.send_keys(Keys.RETURN)

Anyone have any ideas why the downkey is not being registered or am I not using the right syntax?

Upvotes: 5

Views: 7089

Answers (2)

Kushal Bhalaik
Kushal Bhalaik

Reputation: 3384

You can also try actionchains in this case as following:

elem = driver.find_element_by_id("quick-search-query")
elem.send_keys("remote")

suggestion = driver.find_element_by_css_selector("#quick-search > fieldset > div > div > ol:nth-child(1) > li:nth-child(1) a > span")

actions = ActionChains(driver)
actions.move_to_element(suggestion )
actions.click(suggestion)
actions.perform()

Upvotes: 0

alecxe
alecxe

Reputation: 474201

You are still sending the keys to the search input that triggers the search. Instead, find the first quick search dropdown option and send keys to it:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://confluence.eits.uga.edu/dashboard.action")

elem = driver.find_element_by_id("quick-search-query")
elem.send_keys("remote")
elem.send_keys(Keys.ARROW_DOWN)

# wait for the first dropdown option to appear and open it
first_option = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".quick-search-dropdown li a")))
first_option.send_keys(Keys.RETURN)

Upvotes: 5

Related Questions