You need to enable JavaScript to run this app. 使用BeautifulSoup抓取Airbnb时name返回None的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup抓取Airbnb时name返回None的问题咨询

Airbnb爬虫返回name为None的问题原因及修复方案

核心问题原因

  • 动态内容渲染:Airbnb的房源详情页内容大部分是JavaScript动态生成的,你用requests.get()只能拿到初始静态HTML,不包含JS渲染出来的目标数据,所以你定位的_xcsyj0类的div在静态返回里根本不存在,自然返回None
  • 反爬识别:直接用requests发请求没有携带浏览器请求头,大概率会被Airbnb的反爬策略拦截,返回的是非正常页面内容,不会包含房源信息
  • 定位方式不可靠:_xcsyj0是Airbnb动态生成的哈希类名,会随时更新,而且你浏览器里看到的类名和爬虫拿到的页面类名可能不一致,不适合作为定位依据
  • 取值逻辑错误:你当前代码里name取到的是BeautifulSoup的标签对象,就算定位到了元素也需要调用.text或者.get_text()才能拿到文本内容

修复后的代码示例

from bs4 import BeautifulSoup
import requests
import random
from time import sleep
from requests_html import HTMLSession # 该库可模拟浏览器执行JS渲染动态内容

# 配置请求头伪装成正常浏览器访问
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}

def extract_features(listing_html):
    features_dict = {}
    # 改用固定的data-testid属性定位,避免受动态哈希类名影响
    name_elem = listing_html.find('h1', {'data-testid': 'listing-title'})
    # 增加判空逻辑避免元素不存在时报错
    features_dict['name'] = name_elem.get_text(strip=True) if name_elem else None
    return features_dict
      
def getdata(url):
    session = HTMLSession()
    r = session.get(url, headers=HEADERS)
    # 等待页面JS渲染完成
    r.html.render(sleep=2)
    soup = BeautifulSoup(r.html.html, 'lxml')
    session.close()
    # 加随机延迟降低反爬触发概率
    sleep(random.randint(1,3))
    return soup

def getnextpage(soup):
    a_elem = soup.find('a')
    if a_elem and a_elem.get('href'):
        return 'https://www.airbnb.com' + a_elem.get('href')
    return None

url = 'https://www.airbnb.com/s/Bear-Creek-Lake-Dr--Jim-Thorpe--PA--USA/homes?tab_id=home_tab'
soup = getdata(url)
listings = soup.find_all('div','_8s3ctt')

for listing in listings[0:2]:    
    full_url = getnextpage(listing)
    if not full_url:
        continue
    ind_soup = getdata(full_url)
    features = extract_features(ind_soup)
    print(features)
    print("-----------")

额外注意事项

  • 使用requests-html需要提前安装依赖:pip install requests-html,首次运行会自动下载Chromium内核用于页面渲染
  • 如果反爬限制依旧严格,可以考虑换用Selenium、Playwright等更完善的浏览器自动化工具

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 15:45:01