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

如何基于class标签文本提取对应房屋属性值?

房屋爬虫字段一致性提取方案建议

问题场景

爬取多套房屋信息时,每套房屋的字段不统一,直接提取属性值会导致结果结构不一致。需要基于dc_label标签匹配对应属性值,缺失字段设为空,保证数据一致性。

示例代码:

property_info = section_content.find_all('div',{'class':'dc_blocks_2c'})
property_info

输出内容:

<div class="dc_blocks_2c">
 <div class="dc_label">Bedrooms:</div>
 <div class="dc_value">9 Bedroom(s)</div>
 </div>,
 <div class="dc_blocks_2c">
 <div class="dc_label">Baths:</div>
 <div class="dc_value">10 Full  &amp; 4 Half Bath(s)</div>
 </div>,
 <div class="dc_blocks_2c">
 <div class="dc_label">Garage(s):</div>
 <div class="dc_value">4 / Attached</div>
 </div>,
 <div class="dc_blocks_2c">
 <div class="dc_label">Stories:</div>
 <div class="dc_value">2</div>
 </div>,
...

实现方案

核心思路

将每个房屋的属性转换为字典,通过标签文本匹配对应值,最后从字典中提取固定字段,缺失字段自动设为空字符串。

代码实现

# 初始化空字典存储当前房屋属性
property_dict = {}

# 遍历每个属性块
for block in property_info:
    label_elem = block.find('div', class_='dc_label')
    value_elem = block.find('div', class_='dc_value')
    if label_elem and value_elem:
        # 清理标签文本,去除冒号和首尾空格
        clean_label = label_elem.text.strip().rstrip(':')
        # 清理属性值文本
        clean_value = value_elem.text.strip()
        property_dict[clean_label] = clean_value

# 提取固定字段,缺失则返回空字符串
bedroom_num = property_dict.get('Bedrooms', '')
garage_num = property_dict.get('Garage(s)', '')
bath_num = property_dict.get('Baths', '')
stories = property_dict.get('Stories', '')

# 整理为统一结构的字典,方便后续存储或处理
house_data = {
    'bedrooms': bedroom_num,
    'baths': bath_num,
    'garages': garage_num,
    'stories': stories
}

关键说明

  • 文本清理:用strip()去除首尾空格,rstrip(':')去掉标签末尾的冒号,避免因格式差异导致匹配失败;
  • 安全取值:字典的get()方法可以在字段不存在时返回默认值(空字符串),保证每套房屋的结果结构一致;
  • 统一结构:最终的house_data字典键名固定,无论原始数据是否缺失字段,输出结构完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:27:33