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

如何为Selenium Python编写按货币短代码选择按钮的定位器?

解决方案

1. 使用XPath精准定位(推荐)

利用货币代码所在的div文本匹配,结合按钮的data-testid属性缩小范围,能精准定位到对应货币的按钮:

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

def select_currency(driver, currency):
    # 构造XPath,精确匹配货币代码文本
    currency_xpath = f"//button[@data-testid='selection-item']//div[text()='{currency}']/ancestor::button"
    # 等待元素可点击,规避动态加载问题
    currency_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, currency_xpath))
    )
    currency_button.click()

如果担心货币代码文本前后有空格,可加入normalize-space()处理:

currency_xpath = f"//button[@data-testid='selection-item']//div[normalize-space(text())='{currency}']/ancestor::button"

2. CSS选择器替代方案

CSS选择器无法直接匹配文本,但可以结合元素结构+遍历实现:

def select_currency(driver, currency):
    # 等待所有货币按钮加载完成
    currency_buttons = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, "button[data-testid='selection-item']"))
    )
    # 遍历按钮,匹配目标货币代码
    for button in currency_buttons:
        currency_code = button.find_element(By.CSS_SELECTOR, ".f461050668").text.strip()
        if currency_code == currency:
            button.click()
            break

注意事项

  • 确保传入的货币代码是大写格式(如INR、EUR),和页面显示一致
  • 优先用WebDriverWait替代直接find_element,避免页面未加载完成导致的定位失败
  • 若货币选择器是弹窗/下拉层,需先确保该层处于可见状态再执行定位操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:55:12