seleniumxpathautocomplete

How to select subject from an auto complete option?


Website link- https://demoqa.com/automation-practice-form/

I am trying to find xpath for an auto suggested option for Subject field anan


Solution

  • This is one way of interacting with that dropdown:

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import Select
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.keys import Keys
    
    chrome_options = Options()
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument('disable-notifications')
    chrome_options.add_argument("window-size=1280,720")
    
    webdriver_service = Service("chromedriver/chromedriver") ## path to where you saved chromedriver binary
    browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)
    actions = ActionChains(browser)
    
    url = 'https://demoqa.com/automation-practice-form/'
    browser.get(url) 
    
    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.ID, "subjectsInput"))).send_keys('m')
    
    elusive_el = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".subjects-auto-complete__menu")))
    print(elusive_el.get_attribute('outerHTML'))
    maths_option = elusive_el.find_element(By.XPATH, "//div[text()='Maths']")
    maths_option.click()
    print('selected maths')
    

    This should select the Math option, and also print in terminal the html structure of that element, so you can inspect them, and eventually select other child elements as well - you will have to send another string into that input field, wait for the dropdown to initialize, select another option.

    Selenium docs: https://www.selenium.dev/documentation/