Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a value from a drop down in python

I have tried many things it can't seem to get it to work so I am posting this question to hopefully learn the simple method of selecting from a drop down menu in python.

I manage to open the drop down menu but how can I select a value (let's say 4 in this example) from the drop down?

Below is the code that opens the drop down:

#select adults
adults = driver.find_element_by_xpath("//*[@id='adults-number']").click()

Below is the html that consists of all the options in the drop down (the one highlighted is the value I want selected):

enter image description here

like image 924
BruceyBandit Avatar asked Dec 03 '25 15:12

BruceyBandit


1 Answers

Use the Select class and it's .select_by_visible_text() method:

from selenium.webdriver.support.select import Select

adults = Select(driver.find_element_by_id("adults-number"))
adults.select_by_visible_text("4")

Note that I've also replaced the "by xpath" with the simpler and more efficient "by id" locator type.

Working code (using your target website) to select the adults = 4:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
driver.get("http://jet2.com")

wait = WebDriverWait(driver, 10)
adults_element = wait.until(EC.presence_of_element_located((By.ID, "adults-number")))

select = Select(adults_element)
select.select_by_visible_text("4")
like image 147
alecxe Avatar answered Dec 06 '25 03:12

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!