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

使用Python抓取Airbnb数据时无法将字段存入字典问题求助

代码核心问题

  • 逻辑位置颠倒:构造字典、输出的代码被错误放在了except异常捕获块中,仅当抓取字段报错时才会触发执行,正常成功获取到三个字段的场景下反而不会执行存字典的逻辑,这是最主要的错误。
  • 缺少全局存储容器:没有在循环外提前定义列表存储所有房源数据,每次循环生成的字典会被覆盖,无法留存所有爬取结果。
  • 异常处理逻辑缺陷:如果某条房源的字段抓取失败,except块中直接引用price、rating、name变量,若首次循环就抓取失败,这些变量未定义会直接抛出NameError。

修正后的参考代码

import requests
from bs4 import BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'
}

url = 'https://www.airbnb.com/s/Tbilisi--Georgia/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_dates%5B%5D=november&flexible_trip_dates%5B%5D=october&flexible_trip_lengths%5B%5D=weekend_trip&date_picker_type=calendar&query=Tbilisi%2C%20Georgia&place_id=ChIJa2JP5tcMREARo25X4u2E0GE&source=structured_search_input_header&search_type=autocomplete_click'

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'lxml')

# 提前定义列表存储所有房源数据
all_houses = []

for item in soup.find_all('div', itemprop='itemListElement'):
    # 初始化字段默认值,避免未定义报错
    price = rating = name = None
    try:
        price = item.find('span', class_='_krjbj').text
        rating = item.find('span', class_='_18khxk1').text
        name = item.find('meta', itemprop='name')['content']
        # 抓取成功后再构造字典,加入列表
        house_item = {
            'price': price,
            'rating': rating,
            'name': name,
        }
        all_houses.append(house_item)
        print(house_item)
    except Exception as e:
        # 仅打印异常信息,不使用未赋值的变量
        print(f"当前房源抓取失败,错误信息:{e}")

# 爬取完成后可查看整体数据统计
print(f"共爬取到{len(all_houses)}条有效房源数据")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:06:04