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

使用BeautifulSoup提取下拉菜单选中option返回全部列表如何解决

问题原因

你写的find_all({'option': 'selected'})不符合BeautifulSoup的筛选规则,该参数会被识别为匹配「属性名为option、属性值为selected」的元素,和你想要的「匹配option标签且存在selected属性」的逻辑完全不符,因此会返回所有option元素。

正确实现代码

写法1:使用find链式筛选

# 先定位select,再找带selected属性的option
selected_option = soup.find('select', {'name': 'PropertyId'}).find('option', selected=True)
# 提取文本内容
target_text = selected_option.text.strip()

写法2:使用CSS选择器(更简洁)

# 直接通过选择器定位选中的option
selected_option = soup.select_one('select[name="PropertyId"] option[selected]')
# 提取文本内容
target_text = selected_option.text.strip()

两种写法最终得到的target_text就是你需要的Corney Avenue。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:36:06