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

使用BeautifulSoup4提取input标签value属性值遇空值问题求助

问题原因及解决方法

你的问题出在混淆了标签文本和标签属性:<input>是自闭合标签,没有内部文本内容,所以.text或.get_text()自然返回空字符串。你要提取的日期03/31/2023是这个input标签的value属性值,不是标签文本。

正确提取方式

直接通过标签的属性获取即可,以下是两种可行的写法:

写法一:使用.get()方法(推荐,属性不存在时返回None不会报错)

from bs4 import BeautifulSoup

# 假设cmbs_soup是已经解析好的soup对象
date_tag = cmbs_soup.find('input', title='Select as of date', type='text')
if date_tag:
    date = date_tag.get('value')
    print(date)  # 输出:03/31/2023

写法二:直接访问attrs字典

date_tag = cmbs_soup.find('input', {'class': 'mm-date-field form-control input-sm date-picker', 'title': 'Select as of date'})
if date_tag:
    date = date_tag.attrs['value']
    print(date)  # 输出:03/31/2023

补充说明

  • 用find定位标签时,不需要加value=re.compile('.*'),这属于多余操作,我们只需要先定位到目标标签,再提取它的value属性即可。
  • 加上if date_tag:的判断是为了避免标签不存在时抛出AttributeError,让代码更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:32:47