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

如何用BeautifulSoup获取HTML中TRANSPORT下拉框的选中值?

如何用BeautifulSoup获取下拉框的选中值

我来帮你搞定这个问题!首先先把你提供的HTML补全(看起来末尾截断了),然后一步步教你用BeautifulSoup获取TRANSPORT下拉框的选中值。

先准备好环境和完整的HTML

首先确保你已经装了BeautifulSoup4:

pip install beautifulsoup4

这里用你给出的完整HTML内容(修正了无效的{disable}属性,如果你确实需要禁用属性,应该写成disabled,不过这不影响我们取值):

<form id="main"> 
<select id="TRANSPORT" style="font-size: 8pt;margin:0;width:250px;"> 
<option selected value="TCP"> TCP(selected) </option> 
<option value="UDP"> UDP </option> 
</select> 
</form>

两种方法获取选中值

方法一:通过selected属性直接查找

这种方法最直接,先定位到下拉框,再找带有selected属性的选项:

from bs4 import BeautifulSoup

html = '''<form id="main"> 
<select id="TRANSPORT" style="font-size: 8pt;margin:0;width:250px;"> 
<option selected value="TCP"> TCP(selected) </option> 
<option value="UDP"> UDP </option> 
</select> 
</form>'''

# 初始化解析器
soup = BeautifulSoup(html, 'html.parser')

# 找到ID为TRANSPORT的下拉框
transport_select = soup.find('select', id='TRANSPORT')

# 查找带有selected属性的option
selected_opt = transport_select.find('option', selected=True)

if selected_opt:
    # 获取value属性值
    selected_value = selected_opt['value']
    # 获取显示的文本(strip()去掉多余空格)
    selected_text = selected_opt.get_text(strip=True)
    print(f"选中的值是:{selected_value},显示文本:{selected_text}")
else:
    # 处理没有设置selected属性的情况:HTML默认第一个选项选中
    first_opt = transport_select.find('option')
    print(f"默认选中的值是:{first_opt['value']}")

方法二:用CSS选择器简化代码

如果你喜欢用CSS选择器,一行就能定位到选中的选项:

from bs4 import BeautifulSoup

html = '''<form id="main"> 
<select id="TRANSPORT" style="font-size: 8pt;margin:0;width:250px;"> 
<option selected value="TCP"> TCP(selected) </option> 
<option value="UDP"> UDP </option> 
</select> 
</form>'''

soup = BeautifulSoup(html, 'html.parser')

# 用CSS选择器选中TRANSPORT下拉框里带selected属性的option
selected_opt = soup.select_one('#TRANSPORT option[selected]')

if selected_opt:
    print(f"选中的值:{selected_opt['value']}")
else:
    # 默认取第一个选项
    selected_opt = soup.select_one('#TRANSPORT option:first-child')
    print(f"默认选中的值:{selected_opt['value']}")

小提示

  • 你原来HTML里的{disable}是无效的HTML属性,如果是想设置下拉框禁用,应该写成disabled,但这个属性不影响我们获取选中值,因为禁用只是前端不能改,HTML结构里的选中状态依然存在。
  • 如果下拉框没有任何selected属性,按照HTML的默认规则,第一个选项会被自动选中,所以代码里要考虑这种边缘情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:58:32