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

使用Selenium和Python无法点击Booking.com按钮的问题求助

问题解决:Booking.com Selenium 货币/语言按钮点击失败

核心问题分析

  1. CSS选择器语法错误:代码中使用了HTML转义字符",Selenium的CSS选择器无法识别,需替换为真实引号。
  2. 未处理Cookie弹窗:Booking首页的Cookie授权弹窗会干扰目标元素,导致点击失败。
  3. 隐式等待局限性:单纯隐式等待无法适配动态加载的元素,需改用更可靠的显式等待。
  4. 退出逻辑错误:__exit__方法中的while循环会导致程序卡住,无法正常关闭浏览器。

修正后的代码

booking.py

import os
import booking.constants as const
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 selenium.common.exceptions import ElementClickInterceptedException

class Booking(webdriver.Chrome):
    def __init__(self, driver_path=const.chromePath, teardown=True):
        self.driver_path = driver_path
        self.teardown = teardown
        os.environ['PATH'] += self.driver_path
        super(Booking, self).__init__()
        self.implicitly_wait(10)
        self.maximize_window()

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.teardown:
            self.quit()

    def land_first_page(self):
        self.get(const.BASE_URL)
        # 处理Cookie授权弹窗
        try:
            cookie_accept = WebDriverWait(self, 10).until(
                EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler"))
            )
            cookie_accept.click()
        except:
            pass  # 无弹窗则跳过

    def change_currency(self, currency="USD"):
        # 修正CSS选择器,使用真实引号
        currency_trigger = WebDriverWait(self, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[data-testid="header-currency-picker-trigger"]'))
        )
        try:
            currency_trigger.click()
        except ElementClickInterceptedException:
            # 元素被遮挡时用JS强制点击
            self.execute_script("arguments[0].click();", currency_trigger)
        
        # 选择目标货币(示例为USD)
        currency_option = WebDriverWait(self, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, f'a[data-testid="currency-option-{currency.lower()}"]'))
        )
        currency_option.click()

    def change_language(self, language="en-us"):
        language_trigger = WebDriverWait(self, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[data-tooltip-text="Choose your language"]'))
        )
        try:
            language_trigger.click()
        except ElementClickInterceptedException:
            self.execute_script("arguments[0].click();", language_trigger)
        
        # 选择目标语言(示例为英文)
        language_option = WebDriverWait(self, 10).until(
            EC.element_to_be_clickable((By.CSS_SELECTOR, f'a[data-testid="language-option-{language}"]'))
        )
        language_option.click()

run.py

from booking.booking import Booking
with Booking() as bot:
    print('加载首页中...')
    bot.land_first_page()
    print('首页加载完成')
    bot.change_currency()
    print('货币切换完成')
    # bot.change_language()
    # print('语言切换完成')

关键修复说明

  • 修正选择器:将"替换为直接双引号,确保Selenium能正确识别元素。
  • 弹窗处理:显式等待并点击Cookie授权按钮,消除弹窗干扰。
  • 显式等待:针对每个元素单独设置等待条件,适配页面动态加载逻辑。
  • 点击拦截处理:遇到元素遮挡时,使用JS脚本强制触发点击事件。
  • 修复退出逻辑:移除错误的while循环,保证浏览器能正常关闭。

额外注意事项

  • Booking.com页面元素可能随版本更新,若选择器失效,需用浏览器开发者工具(F12)重新定位最新元素属性。
  • 频繁操作易触发反爬机制,建议在操作间添加合理延迟(如time.sleep(1))或随机间隔。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:01:01