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

如何用BeautifulSoup和Python获取下拉框选中选项?

获取下拉框选中选项值的问题解决

错误原因

  • 你代码里用find('input', {'name': 'sexo'})查找元素,但目标是<select>标签而非<input>,导致返回None,调用get()时触发AttributeError: 'NoneType' object has no attribute 'get'。
  • 即便找到<select>标签,直接取它的value属性也不对,选中的值在<option>子标签的value属性里,且该option带有selected属性。

正确实现代码

方法一:分步查找(带异常判断)

from bs4 import BeautifulSoup

soup = BeautifulSoup(login_request.text, 'lxml')
# 定位到name为sexo的select标签
select_element = soup.find('select', {'name': 'sexo'})

if select_element:
    # 找到带有selected属性的option标签
    selected_option = select_element.find('option', {'selected': ''})
    if selected_option:
        selected_value = selected_option.get('value')
        print(selected_value)  # 输出选中的M
    else:
        print("未选中任何选项")
else:
    print("找不到name为sexo的下拉框")

方法二:CSS选择器简洁写法

from bs4 import BeautifulSoup

soup = BeautifulSoup(login_request.text, 'lxml')
# 直接通过CSS选择器定位选中的option
selected_option = soup.select_one('select[name="sexo"] option[selected]')
if selected_option:
    print(selected_option.get('value'))  # 输出M

注意事项

  • 若页面结构可能变化,建议保留判断逻辑,避免因元素不存在触发报错。
  • 部分页面中selected属性可能是selected="selected",此时查找条件改为{'selected': 'selected'}即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:55:24