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

无需Selenium,如何等待HTML渲染以抓取租房网站数据?

解决方案:直接调用网站后端API接口

这类依赖JavaScript渲染内容的网站,通常会通过后端API接口异步加载数据,绕过JS渲染直接调用API是最高效且稳定的方案,完全不需要Selenium或无头浏览器。

步骤1:定位目标API接口

打开浏览器开发者工具(F12),切换到「Network」标签,刷新页面后筛选「XHR」或「Fetch」请求,能发现网站实际通过以下接口获取房源数据:

https://www.huurstunt.nl/api/search/listings

该接口支持通过查询参数指定城市、分页等条件,核心参数示例:

  • location: 城市名称(如eindhoven)
  • page: 页码
  • limit: 每页房源数量(默认24)
  • sort: 排序规则(如relevance按相关性、price-asc按价格升序)

步骤2:构造请求调用API

用requests直接请求该API,带上必要请求头模拟浏览器行为,避免被拦截,示例代码:

import requests

def get_huurstunt_listings(city, page=1, limit=24):
    url = "https://www.huurstunt.nl/api/search/listings"
    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": "application/json, text/plain, */*",
        "Referer": f"https://www.huurstunt.nl/huren/{city}/"
    }
    params = {
        "location": city,
        "page": page,
        "limit": limit,
        "sort": "relevance"
    }
    
    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    return response.json()

# 调用示例:获取埃因霍温第1页房源
data = get_huurstunt_listings("eindhoven", page=1)
for listing in data.get("listings", []):
    print(f"标题: {listing['title']}")
    print(f"租金: {listing['price']} €/月")
    print(f"地址: {listing['address']}")
    print(f"详情页: https://www.huurstunt.nl{listing['url']}")
    print("---")

步骤3:提取全量房源数据

通过API返回的pagination字段获取总页数,循环遍历所有页码即可拿到全部房源:

import time

def get_all_huurstunt_listings(city):
    all_listings = []
    # 先获取第1页数据,拿到总页数
    first_page = get_huurstunt_listings(city, page=1)
    all_listings.extend(first_page.get("listings", []))
    total_pages = first_page.get("pagination", {}).get("totalPages", 1)
    
    # 遍历剩余页码,添加间隔避免反爬
    for page in range(2, total_pages + 1):
        time.sleep(1)
        page_data = get_huurstunt_listings(city, page=page)
        all_listings.extend(page_data.get("listings", []))
    return all_listings

# 获取埃因霍温全部房源
all_data = get_all_huurstunt_listings("eindhoven")
print(f"共获取到 {len(all_data)} 套房源")

部署注意事项

  • 请求频率:每页请求间添加1-2秒间隔,避免触发网站反爬机制
  • 请求头维护:定期更新User-Agent,模拟真实浏览器请求
  • 错误处理:添加异常捕获(如网络超时、API返回异常),保证应用稳定性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:02:51