You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium自动化选择表单下拉框报错,求正确实现方案

问题解决步骤

错误原因分析

  1. Selenium版本兼容问题:当前使用的是Selenium 4.x版本,该版本已移除find_element_by_xpath、find_element_by_id这类旧版定位方法,统一改用find_element(定位策略, 定位表达式)的语法。
  2. 元素定位错误:页面中的下拉栏是<select>标签,而非你代码中写的<input>,定位时需修正标签类型。
  3. 冗余代码:代码重复导入了webdriver模块,可删除重复项。

修正后的完整代码

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import Select

# 初始化浏览器服务与实例
servico = Service(ChromeDriverManager().install())
navegador = webdriver.Chrome(service=servico)
navegador.implicitly_wait(10)

# 打开目标页面
navegador.get('http://site.com.br')

# 导航到目标页面(原有步骤保留)
navegador.find_element('xpath', "//a[@id='linkMenu_1500']").click()
navegador.find_element('xpath', "//a[@id='menu_1501']").click()
navegador.find_element('xpath', "//a[@id='subMenu1000006']").click()

# 定位下拉框并选择目标选项
select_element = navegador.find_element('id', 'id_formulario')
select = Select(select_element)
# 通过value值选择(最可靠,value属性固定不变)
select.select_by_value('1000013')
# 也可通过可见文本选择(需完全匹配显示文本,包括空格)
# select.select_by_visible_text('Relatório de Emissão Tokio ID1000013')

关键修正说明

  • 替换旧版定位方法:将navegador.find_element_by_xpath(...)改为navegador.find_element('xpath', ...),此处直接用id定位下拉框更高效。
  • 修正标签类型:定位下拉框时,原代码错误地用了<input>标签,实际应为<select>,通过id='id_formulario'定位是最直接的方式。
  • 规范下拉框操作:使用Select类封装下拉框元素,调用select_by_value或select_by_visible_text完成选项选择,其中select_by_value稳定性更高,不受文本显示变化影响。

内容的提问来源于stack exchange,提问作者Victor Soares

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:25:02