You need to enable JavaScript to run this app. BeautifulSoup爬取Booking.com时变量处理、酒店筛选及价格对比问题
优惠活动
大模型
产品
解决方案
定价
更多

BeautifulSoup爬取Booking.com时变量处理、酒店筛选及价格对比问题

问题根因与修复方案
  • 匹配失效的核心诱因:get_text() 会保留HTML节点内所有的首尾空白、换行、缩进字符,实际爬取到的酒店名称文本前后附带大量不可见空白,和硬编码的纯文本目标值字符串长度、内容都不一致,等值判断永远无法命中,因此只会反复输出Wrong Hotel。
  • 强制加str()无效的原因:get_text()返回值本身就是字符串类型,强制类型转换不会移除字符串内夹带的空白字符,无法解决匹配不相等的问题。
  • 无输出的诱因:原代码的异常捕获逻辑直接打印空字符串,把选择器匹配失败、元素不存在等真实错误全部隐藏,出现提取失败时没有任何报错提示。
  • 文本清洗是匹配的前置步骤:提取酒店名称、价格文本后,调用strip()方法移除所有首尾空白字符,就能拿到无冗余的干净文本。
  • 匹配逻辑可做容错优化:将严格等值判断替换为包含判断,避免因大小写、额外标点、字符截断导致匹配失效。
  • 异常处理需保留报错信息:不要在捕获异常后直接输出空内容,把真实错误打印出来,才能快速定位爬取问题。

修改后可正常运行的代码:

from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'}

# 替换为你实际使用的目标URL
url = 'https://www.booking.com/searchresults.en-gb.html?aid=355028&sid=d2a902f346650dc0b748848763652bdc&sb=1&src=searchresults&src_elem=sb&error_url=https%3A%2F%2Fwww.booking.com%2Fsearchresults.en-gb.html%3Faid%3D355028%3Bsid%3Dd2a902f346650dc0b748848763652bdc%3Btmpl%3Dsearchresults%3Bcheckin_month%3D5%3Bcheckin_monthday%3D8%3Bcheckin_year%3D2021%3Bcheckout_month%3D5%3Bcheckout_monthday%3D13%3Bcheckout_year%3D2021%3Bcity%3D-2601889%3Bclass_interval%3D1%3Bdest_id%3D-2601889%3Bdest_type%3Dcity%3Bdtdisc%3D0%3Bfrom_sf%3D1%3Bgroup_adults%3D1%3Bgroup_children%3D0%3Binac%3D0%3Bindex_postcard%3D0%3Blabel_click%3Dundef%3Bno_rooms%3D1%3Boffset%3D0%3Bpostcard%3D0%3Broom1%3DA%3Bsb_price_type%3Dtotal%3Bshw_aparth%3D1%3Bslp_r_match%3D0%3Bsrc%3Dsearchresults%3Bsrc_elem%3Dsb%3Bsrpvid%3D6eda76c5afe000a5%3Bss%3DLondon%3Bss_all%3D0%3Bssb%3Dempty%3Bsshis%3D0%3Bssne%3DLondon%3Bssne_untouched%3DLondon%3Btop_ufis%3D1%3Bsig%3Dv1yWyN9mHA%3B&ss=London+Marriott+Hotel+County+Hall%2C+London%2C+Greater+London%2C+United+Kingdom&is_ski_area=&ssne=London&ssne_untouched=London&city=-2601889&checkin_year=2021&checkin_month=5&checkin_monthday=8&checkout_year=2021&checkout_month=5&checkout_monthday=13&group_adults=1&group_children=0&no_rooms=1&from_sf=1&ss_raw=Marriott+London&ac_position=1&ac_langcode=en&ac_click_type=b&dest_id=36867&dest_type=hotel&place_id_lat=51.5010959924622&place_id_lon=-0.119165182113647&search_pageview_id=6eda76c5afe000a5&search_selected=true&search_pageview_id=6eda76c5afe000a5&ac_suggestion_list_length=5&ac_suggestion_theme_list_length=0'

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, "lxml")

target_hotel_name = 'London Marriott Hotel County Hall'

for item in soup.select('.sr_property_block'):
    try:
        # 提取文本后立即清洗首尾空白
        hotelname = item.select('.sr-hotel__name')[0].get_text().strip()
        hotelprice = item.select('.bui-price-display__value')[0].get_text().strip()

        # 采用包含判断降低匹配容错
        if target_hotel_name in hotelname:
            print(hotelname)
            print(hotelprice)
        
    except Exception as e:
        # 打印真实异常,避免吞错
        print(f"提取失败:{e}")

关于爬取变量能否参与后续操作的说明:get_text()提取到的字符串完全可以正常做比较、格式转换等操作,后续做价格对比功能时,只需要把提取到的价格文本做清洗(移除货币符号、千分位分隔符)转成数值类型,就可以直接参与计算,不存在爬取变量不可操作的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 01:15:01