undetected Selenium
undetected Selenium

Reputation: 193088

How to select an option from the auto suggestions using Selenium and Python

I'm trying to select an option from the auto-suggestions after sending a text within the search field of the Selenium documentation website. But I'm unable to find any of those suggestions.

Code trials:

driver.get('https://www.selenium.dev/documentation/en/')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#search-by"))).send_keys("selenium")

Snapshot of the auto-suggestions:

documentations

Can anyone help me out please to select any of the auto-suggestions?

Upvotes: 0

Views: 2318

Answers (2)

Wilfred Clement
Wilfred Clement

Reputation: 2774

+1 for @Moshe Slavin's answer. The autocomplete-suggestions is the div that holds all the autocomplete-suggestion's

In order to capture the elements, I used the getPageSource() to print out the elements in the page.

And once I figured out the element the rest of the code below is self explanatory

wait.until(ExpectedConditions.elementToBeClickable(By.className("autocomplete-suggestion")));

List<WebElement> abc = driver.findElements(By.className("autocomplete-suggestion"));

String value = "Remote WebDriver client";

List<String> def = new ArrayList<String>();

    for (int i = 0; i < abc.size(); i++) {

            //Get the values and store it in a list
            def.add(abc.get(i).getAttribute("data-title"));

        }

        if (def.contains(value))

            abc.get(def.indexOf(value)).click();

        else
            System.out.println("Value not present");

Upvotes: 3

Moshe Slavin
Moshe Slavin

Reputation: 5204

The autocomplete-suggestions is the div that holds all the autocomplete-suggestion's.

Here is a snip of the elements enter image description here

To capture the elements I used the f8 button when searching for selenium, that way the elements don't disappear.

Here is a code snip for visualization:

def highlight_element(element):
    driver_elem = element.parent

    def apply_style(s):
        driver_elem.execute_script("arguments[0].setAttribute('style', arguments[1]);",
                                   element, s)

    original_style = element.get_attribute('style')
    apply_style("background: yellow; border: 2px solid red;")
    sleep(0.5)
    apply_style(original_style)

driver.get("https://www.selenium.dev/documentation/en/")
WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#search-by")))
driver.find_element_by_css_selector("#search-by").send_keys("selenium")
WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".autocomplete-suggestions  .autocomplete-suggestion")))
for ele in driver.find_elements_by_css_selector(".autocomplete-suggestions  .autocomplete-suggestion"):
    highlight_element(ele)

Upvotes: 3

Related Questions