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

使用Selenium修改Booking.com货币的问题及解决方案

解决Selenium切换Booking.com货币到USD时选中错误选项的问题

问题描述

用Selenium操作Booking.com切换货币为USD时,点击选项总是选中列表第一个货币(欧元)。原代码用find_element的CSS选择器定位元素,无法精准选中USD;尝试Xpath定位时,又错误选中印度卢比。

原错误代码

currency_element.click()
selected_currency = self.find_element(
    By.CSS_SELECTOR,'button[data-testid="selection-item"][class="a83ed08757 aee4999c52 ffc914f84a c39dd9701b ac7953442b"]'
)
selected_currency.click()

问题根源:find_element仅返回匹配到的第一个元素,因此每次都会点击列表最上方的欧元选项。

解决方案代码

def change_currency(self,currency=None):
    time.sleep(5)
    currency_element = self.find_element(
        By.XPATH,"/html/body/div[2]/div/header/nav[1]/div[2]/span[1]/button"
    )
    currency_element.click()
    selected_currency = self.find_elements(
        By.CSS_SELECTOR,'button[data-testid="selection-item"][class="a83ed08757 aee4999c52 ffc914f84a c39dd9701b ac7953442b"]'
    )
    for element in selected_currency:
        try:
            curr = element.text.split("\n")[-1]
            if curr == "USD":
                time.sleep(4)
                element.click()
            else:
                pass
        except:
            pass

方案说明

  1. 获取所有选项:用find_elements替代find_element,获取页面上所有符合条件的货币选项元素
  2. 精准匹配货币:遍历每个元素,通过分割文本提取货币代码(取文本最后一段,对应USD等标识)
  3. 等待元素加载:添加time.sleep确保弹窗和元素完全加载,避免操作失败
  4. 异常处理:捕获遍历过程中的异常,避免代码中断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:57:26