[英]Non-Select Drop-down list selection using Selenium Python
我正在尝试打印选项并从本网站的“城市”下拉搜索框中选择“曼哈顿”: https ://upxland.me/properties/。 但是每次我运行它时,程序都没有打印任何东西就结束了。 另外,谁能告诉我如何输入城市名称的一部分(如“Manha”),然后从下拉列表中选择?
我的代码如下所示。 有人可以帮忙吗?
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
import time
PATH = "/usr/local/bin/chromedriver"
driver = webdriver.Chrome(PATH)
driver.get("https://upxland.me/properties/")
try:
city = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, 'input-74')))
# city.send_keys("o")
# city.send_keys(Keys.RETURN)
city_selection = Select(city)
# print the number of option
print(len(city_selection.options))
# print all options
for option in city_selection.options:
print(option.text)
# select by index
city_selection.select_by_index(3)
time.sleep(3)
# select by value
# city_selection.select_by_value()
except:
driver.quit()
所需的元素不在任何html-select标记内,但它们在<div>
标记内。
所以你将无法使用Select()类。
要打印选项文本,您可以使用List Comprehension并且可以使用以下定位器策略:
代码块:
driver.execute("get", {'url': 'https://upxland.me/properties/'}) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Accept all']"))).click() WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[text()='City']//following-sibling::input[1]"))).click() print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='v-menu__content theme--dark menuable__content__active v-autocomplete__content']//div[@role='option']//div[@class='v-list-item__title']")))])
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
控制台输出:
['Los Angeles', 'San Francisco', 'Manhattan', 'Queens', 'Fresno', 'Brooklyn', 'Oakland', 'Staten Island', 'Bakersfield', 'Chicago', 'Cleveland', 'Santa Clara', 'Rutherford', 'Kansas City', 'New Orleans', 'Nashville', 'Bronx', 'Detroit', 'Las Vegas']
选择曼哈顿:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='v-menu__content theme--dark menuable__content__active v-autocomplete__content']//div[@role='option']//div[@class='v-list-item__title' and text()='Manhattan']"))).click()
您需要在城市的输入框中单击并输入一些文本。 然后加 1 秒等待。 然后使用选项 xpath 获取元素列表。
通过遍历列表获取每个元素的文本,直到获得所需的城市,然后单击它。
选择元素的 xpath 是 -
//input[@placeholder="City"]
选择元素选项的 xpath 是 -
//div[contains(@class,'content__active v-autocomplete__content')]//div[@class='v-list-item__title']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.