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

BeautifulSoup的find_all搭配循环仅返回首条 如何获取Airbnb房源列表总页数

Airbnb分页最大页码提取解决方案
  • 现有代码缺失BeautifulSoup实例初始化步骤,请求返回的响应内容未解析为可操作的DOM对象
  • 直接发起无请求头的GET请求会触发Airbnb反爬机制,返回的静态页面内容不全,导致分页节点提取不完整
  • 部分页码节点未渲染时,可通过过滤数字文本的方式获取有效页码再取最大值

修正后完整代码

依赖导入与请求头配置

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/120.0.0.0 Safari/537.36",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}

参数配置与URL构造

# 可编辑爬虫参数
checkin_checkout = 'checkin=2021-05-28&checkout=2021-05-30'
adults = 12
n_beds = adults // 2

# 拼接请求URL,移除多余换行避免格式错误
nearby = f'https://www.airbnb.com/s/homes?tab_id=home_tab&refinement_paths%5B%5D=%2Fhomes&flexible_trip_dates%5B%5D=july&flexible_trip_dates%5B%5D=june&flexible_trip_lengths%5B%5D=weekend_trip&date_picker_type=calendar&location_search=NEARBY&{checkin_checkout}&adults={adults}&source=structured_search_input_header&search_type=filter_change&room_types%5B%5D=Entire%20home%2Fapt&place_id=ChIJu-A79dZz44kRGu2B8kV8ylQ&min_beds={n_beds}'

res = requests.get(nearby, headers=headers)
# 初始化soup解析对象
soup = BeautifulSoup(res.text, 'html.parser')

最大页码提取逻辑

page_num_list = []
# 匹配所有分页a标签
for page_tag in soup.select('div[class*="_jro6t0"] a'):
    page_text = page_tag.get_text(strip=True)
    # 过滤非数字的按钮(比如下一页、省略号)
    if page_text.isdigit():
        page_num_list.append(int(page_text))

max_page = max(page_num_list) if page_num_list else 1
print(f"最大页码为{max_page}")

补充说明

如果静态请求始终无法拿到全量分页节点,可换用Selenium、Playwright等动态页面渲染工具加载完整页面后再提取节点,即可获取全部页码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 06:24:03