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

如何仅用Python Requests获取JS动态加载的房车租赁页面价格?

问题描述

尝试获取指定房车租赁页面(安纳西地区,2025年1月6日至10日)的价格信息,先后使用requests和requests-html工具均未成功。代码中无法找到页面上显示的content-right元素,推测该内容由JavaScript动态加载。需求是不使用Selenium,仅通过Python Requests相关工具获取加载后的价格信息。

附尝试的代码:

from requests_html import HTMLSession
session = HTMLSession()
from bs4 import BeautifulSoup

response = session.get('https://campervans.jeanlain.com/locations/?city-input=annecy&city-name=ANNECY&departure_date=06%2F01%2F2025&departure_time=11%3A00&return_date=10%2F01%2F2025&return_time=10%3A00')
response.html.render()

soup = BeautifulSoup(response.html.html, 'html.parser')
products = soup.find_all('section', class_='product')

for product in products:
    title = product.find('h2', class_='woocommerce-loop-product__title')
    if title:
        print(title.text)
    
    price_info = product.find('div', class_='content-right')
    if price_info:
        price = price_info.find('p', class_='price')
        print(price)
    else:
        print("content-right not found")
解决方案

这类动态加载内容的核心是找到页面渲染时调用的后端API接口,直接请求接口获取原始数据,比渲染页面更高效可靠。

步骤1:抓包定位数据接口

  1. 打开目标页面,按下F12打开浏览器开发者工具,切换到「Network」标签页。
  2. 刷新页面,筛选「XHR」或「Fetch」类型的请求,寻找返回房车列表/价格数据的接口(通常返回JSON格式)。
  3. 查看该接口的请求URL、参数和请求头,记录必要信息。

步骤2:模拟请求接口并解析数据

以下是基于抓包结果的示例代码(需根据实际接口调整参数):

import requests

# 替换为抓包得到的实际接口URL
api_url = "https://campervans.jeanlain.com/wp-admin/admin-ajax.php"

# 接口请求参数,对应页面的查询条件
payload = {
    'action': 'load_rental_products',
    'city': 'ANNECY',
    'departure_date': '06/01/2025',
    'departure_time': '11:00',
    'return_date': '10/01/2025',
    'return_time': '10:00'
}

# 模拟浏览器请求头,避免被拦截
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',
    'Referer': 'https://campervans.jeanlain.com/locations/?city-input=annecy&city-name=ANNECY&departure_date=06%2F01%2F2025&departure_time=11%3A00&return_date=10%2F01%2F2025&return_time=10%3A00'
}

# 发送请求并解析JSON
response = requests.get(api_url, params=payload, headers=headers)
product_data = response.json()

# 提取所需信息
for item in product_data.get('items', []):
    print(f"房车名称: {item['title']}")
    print(f"租赁价格: {item['price_display']}")
    print("---")

补充说明

  • 如果坚持使用requests-html,可以尝试延长渲染等待时间,确保JS完全加载:
    response.html.render(timeout=30, sleep=5)  # sleep参数表示等待JS执行的时间
    
    但这种方法稳定性不如直接调用API,且容易受页面结构变化影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:41:01