DLP
DLP

Reputation: 1

How to select/click in a dropdown content using selenium chromewebdriver / python

My website form have updated and my script is no more working. I cannot fix it because I'm not able to find how to select in a dropdown content using selenium chrome web driver and python.

formattedstate is the value of a formatted data (read from a file)

driver.find_element_by_css_selector(f"option[title='{formattedState}']").click()

driver.find_element_by_xpath("//*[text()='{formattedState}']").click()

driver.find_element_by_css_selector(f"option[value='{formattedState}']").click()

This is the data of the dropdown content from the webform. I selected the first state in the dropdown = Alabama

<input aria-valuetext="" role="combobox" tabindex="0" 
placeholder="State/Province/Region" readonly="" height="100%" size="1" autocomplete="off" value="" data-spm-anchor-id="a2g0o.placeorder.0.i14.5f0b321eC7zfLx">



<li class="next-menu-item" title="Alabama" data-spm-anchor-id="a2g0o.placeorder.0.i17.5f0b321eC7zfLx">Alabama</li>

It should select the correct state in the dropdown content

Upvotes: 0

Views: 1580

Answers (2)

Naveen
Naveen

Reputation: 788

JS SetAttribute works surprisingly well for Combobox. Try

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('value', '//value to set')");
// to click
js.executeScript("arguments[0].click();", element);

Upvotes: 0

Sers
Sers

Reputation: 12255

First try to click to the combobox, then wait until state option(li) element is visible and click.

In code below, I used css selector to get li by title. If you want to find element by text, use:
wait.until(ec.visibility_of_element_located((By.XPATH, f"//li[.='{state}' and @class = 'next-menu-item']"))).click()

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

state = "Alabama"
driver.find_element_by_css_selector('input[placeholder="State/Province/Region"]').click()
wait.until(ec.visibility_of_element_located((
    By.CSS_SELECTOR, f"li.next-menu-item[title='{state}']"))).click()

Upvotes: 1

Related Questions