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

为何BeautifulSoup无法抓取Booking.com的折扣价格元素?

解决Booking.com折扣价格抓取缺失的问题

核心原因

Booking.com的折扣价元素是通过JavaScript动态渲染生成的,直接用requests+BeautifulSoup请求只能拿到页面初始的静态HTML,无法获取JS执行后加载的动态内容,这就是你只能抓到原价、找不到折扣价元素的关键原因。

可行解决方案

1. 用Selenium模拟浏览器渲染

Selenium可以模拟真实浏览器的加载流程,等待JS执行完毕后再获取完整页面HTML,就能拿到包含折扣价的元素。示例代码如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

# 初始化Chrome浏览器(需提前安装对应版本的chromedriver)
driver = webdriver.Chrome()
target_url = "https://www.booking.com/searchresults.de.html?label=gen173nr-1DCAEoggI46AdIM1gEaA6IAQGYAQe4ARjIAQzYAQPoAQGIAgGoAgS4AozdqpoGwAIB0gIkMTc4YWJjZjQtMjIyZC00MmU2LTg5NGUtYTI2OTEyYWJmZDkz2AIE4AIB&sid=c3a0002efd8923ea8cb7a6157f83f910&aid=304142&ss=Rovinj&ssne=Rovinj&ssne_untouched=Rovinj&lang=de&src=searchresults&dest_id=-94604&dest_type=city&checkin=2023-04-14&checkout=2023-04-21&group_adults=2&no_rooms=1&group_children=0&sb_travel_purpose=leisure&nflt=oos%3D1"

driver.get(target_url)
# 等待折扣价元素加载完成(可根据实际页面调整选择器,比如折扣价的class可能是`bui-price-display__value`)
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CLASS_NAME, "bui-price-display__value")))

# 获取完整页面源码
page_html = driver.page_source
driver.quit()

# 用BeautifulSoup解析
soup = BeautifulSoup(page_html, "html.parser")
# 提取折扣价(根据实际元素调整选择器)
discount_prices = soup.find_all("span", class_="bui-price-display__value")
for price in discount_prices:
    print(price.text.strip())

2. 直接请求后端API接口

打开Chrome开发者工具的「网络」面板,刷新页面后过滤XHR/Fetch请求,找到返回价格数据的API接口,直接请求该接口获取JSON格式的价格信息,这种方式比模拟浏览器更高效:

  • 操作步骤:
    • 打开目标页面按F12进入开发者工具
    • 切换到「网络」标签,勾选「XHR」选项
    • 刷新页面,找到包含价格数据的请求(URL通常带prices、search等关键词)
    • 复制该请求的URL、请求头和参数,用requests库直接发送请求并解析返回的JSON数据

注意事项

  • Booking.com有反爬机制,频繁请求可能被封禁IP,建议添加User-Agent模拟浏览器、设置请求间隔,必要时使用代理IP。
  • 页面元素的class或选择器可能随时更新,需要定期检查并调整解析规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:01:19