简体   繁体   English

获取下拉菜单的文本

[英]Get text of drop-down menu

I have a drop-down menu.我有一个下拉菜单。

I want to get all cities from AZ using Python's Selenium.我想使用 Python 的 Selenium 从 AZ 获取所有城市。

<li> is a list of every city starting with an A . <li>是以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' ???

在此处输入图像描述 在此处输入图像描述

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:为了使用预期的条件wait object 你将不得不使用这些导入:

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 object 与

wait = WebDriverWait(driver, 20)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM