hallopeterswelt
hallopeterswelt

Reputation: 53

Get text of drop-down menu

I have a drop-down menu.

I want to get all cities from A-Z using Python's Selenium.

<li> is a list of every city starting with an A.

But how to get the text now? My proceeding:

# Open drop-down menu
driver.find_element(BY.XPATH, '//*[@id="city-field"]/div/div/div[1]/button').click()

# Type in 'A'
driver.find_element(BY.XPATH, '//*[@id="city-field"]/div/div/div[1]/div/div[1]/input').send_keys('A')

# Get every cities starting with 'A' ???

enter image description here enter image description here

Upvotes: 1

Views: 835

Answers (2)

Prophet
Prophet

Reputation: 33371

You should get all the element containing city names and then iterate over that list extracting the city name texts.
Something like this:

# Open drop-down menu
driver.find_element(BY.XPATH, '//*[@id="city-field"]/div/div/div[1]/button').click()

# Type in 'A'
driver.find_element(BY.XPATH, '//*[@id="city-field"]/div/div/div[1]/div/div[1]/input').send_keys('A')
wait.until(EC.visibility_of_element_located((By.XPATH, "//ul[@class='dropdown-menu inner']//span[@class='text']")))
city_names = driver.find_elements(BY.XPATH, "//ul[@class='dropdown-menu inner']//span[@class='text']")
names = []
for city in city_names:
    name = city.text
    names.append(name)

In order to use expected conditions wait object you will have to use these imports:

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

And to initialize wait object with

wait = WebDriverWait(driver, 20)

Upvotes: 1

Anand Gautam
Anand Gautam

Reputation: 2101

Something like this should work. It would've better if you provided the code instead of image, or the website link would've been even better to investigate. Anyway, try like this:

options = driver.find_elements(By.XPATH, "//div[@class='dropdown-menu open']//*[@role='option]"

ls = [option.text for option in options]
print(ls)

Upvotes: 1

Related Questions