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

Python爬虫:如何将列表特定索引组元素分别追加至对应房产信息列表

房产数据提取:分离卧室、浴室数量及房屋面积

爬取某房产网站信息时,需提取卧室数量、浴室数量及房屋面积,但数据按固定顺序排列,需按索引分组提取。

现有代码

Bedroom = []
Bathroom = []
# 注意:Python变量名不能包含空格,此处原变量名"Size of Building"非法,需修改为合法名称
Size_of_Building = []

houses = []
Hux_clean = []

details = province_soup.find_all("li", class_="mr-3 flex items-center")
for detail in details:
    houses.append(detail.get_text())

for house in houses:
    Hux_clean.append(house.strip())
    
for value, count in enumerate(Hux_clean):
    print(value, count)
    if value==0:
        Bedroom.append(count)

代码执行输出

0 2
1 2
2 168 m²
3 3
4 2
5 110 m²
6 7
7 4
8 260 m²
9 4
10 4
11 334 m²
12 3
13 2
14 301 m²
15 3
16 2
17 106 m²
18 4
19 4
20 624 m²
21 2
22 1
23 60 m²
24 3
25 3
26 379 m²
27 3
28 3
29 323 m²
30 2
31 1
32 81 m²
33 3
34 2
35 122 m²
36 3
37 1
38 85 m²
39 5
40 4
41 473 m²
42 3
43 3
44 125 m²
45 5
46 5
47 377 m²
48 3
49 2
50 85 m²
51 4
52 4
53 965 m²
54 3
55 2
56 106 m²
57 2
58 2
59 85 m²

需求与解决方案

需求:将Hux_clean列表中索引为0、3、6…的元素加入Bedroom列表;索引1、4、7…加入Bathroom列表;索引2、5、8…加入Size_of_Building列表。

修改循环逻辑,通过索引对3取模实现分组:

Bedroom = []
Bathroom = []
Size_of_Building = []

houses = []
Hux_clean = []

details = province_soup.find_all("li", class_="mr-3 flex items-center")
for detail in details:
    houses.append(detail.get_text())

for house in houses:
    Hux_clean.append(house.strip())
    
for idx, item in enumerate(Hux_clean):
    print(idx, item)
    # 按索引模3的结果分配到对应列表
    if idx % 3 == 0:
        Bedroom.append(item)
    elif idx % 3 == 1:
        Bathroom.append(item)
    elif idx % 3 == 2:
        Size_of_Building.append(item)

关键说明

  • 原代码中变量名Size of Building不符合Python语法规则(变量名不能包含空格),需修改为Size_of_Building或其他合法名称。
  • 使用idx % 3判断元素所属分组,确保每3个连续元素分别对应卧室、浴室、面积信息,适配数据的排列规律。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:39:21