使用Python Selenium获取下拉列表选项值失败,仅能获取文本的解决方法
解决Selenium获取下拉选项值的问题
要获取下拉列表选项对应的value属性值,无需额外编写XPath,直接通过选项元素的get_attribute("value")方法即可实现。以下是修改后的完整代码:
from selenium.common.exceptions import WebDriverException from selenium import webdriver from selenium.webdriver.support.ui import Select # 补充Select类的导入 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.3" } options = webdriver.ChromeOptions() options.add_argument("--headless") options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument(f'user-agent={headers["User-Agent"]}') # 让UA配置生效 URL = ['https://www.classicalmusicartists.com/cma/artists.aspx'] for url in URL: try: driver = webdriver.Chrome(executable_path='/home/ubuntu/selenium_drivers/chromedriver', options=options) driver.get(url) driver.implicitly_wait(2) datas = driver.find_element("xpath", '//select[@id="ctl00_cphMainContent_lstCategory"]') d = Select(datas) for opt in d.options: # 同时获取选项文本和对应的value值 opt_text = opt.text opt_value = opt.get_attribute("value") print(f"选项文本: {opt_text}, 对应值: {opt_value}") driver.quit() except WebDriverException: driver.quit()
关键修改说明
- 补充了
Select类的导入,否则代码会报错; - 通过
opt.get_attribute("value")直接提取选项的value属性值,这是最直接的方式; - 将原代码中未生效的
User-Agent配置添加到ChromeOptions中,确保请求UA符合预期; - 如果只需要输出
value值,直接打印opt.get_attribute("value")即可。
内容的提问来源于stack exchange,提问作者imhans4305
相关产品推荐
相关产品推荐

