How to select option from a combobox in python selenium?

Question:

I am trying to put value in a combo-box using python selenium. As we enter text it gives different possible values in dropdown. How to select the first value on the drop down? As soon as I try to click on it, it removes the text and makes it blank.

enter image description here
enter image description here

So, for example, I am sending the text Stockholms kommun, Stockholms län in the combobox by:

text = Stockholms kommun, Stockholms län
inputcity = driver.find_element(By.XPATH, '//*[@id="price-calculator-address"]')
inputcity.send_keys(text)

However, I am not able to click (as shown in image-2) on the dropdown which appears as I enter the text.

Link of website: https://www.hemnet.se/annonsera-bostad#priskalkylatorn

Can anyone help me with it?

Asked By: Gopal Chitalia

||

Answers:

Trick is to enter the text and press Tab twice. Basically imitate the manual actions if it was to be done via human.

Try the below working code:

driver = webdriver.Chrome()
driver.get("https://www.hemnet.se/annonsera-bostad#priskalkylatorn")
driver.maximize_window()
# below line will accept cookies
driver.find_element(By.XPATH, "//button[text()='Jag samtycker']").click()
driver.find_element(By.XPATH, "//*[@id='price-calculator-address']").send_keys("Stockholms kommun, Stockholms län")
time.sleep(3)
# below line will press TAB key 2 times
driver.find_element(By.XPATH, "//*[@id='price-calculator-address']").send_keys(Keys.TAB + Keys.TAB)

Result:
enter image description here

Answered By: Shawn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.