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

如何使用Selenium从动态下拉菜单中选择指定选项

自动化选择下拉菜单出发地城市实现方案

实现步骤

  • 调用goToConfiguration方法跳转至配置页面,等待页面所有元素加载渲染完成
  • 定位出发地字段对应的dropdownMenuButton组件,触发点击事件展开下拉选项列表
  • 在展开的列表中定位目标城市选项,点击完成选择操作,可额外增加校验步骤确认选择生效

参考代码

Flutter 集成测试版本

import 'package:flutter_test/flutter_test.dart';

void selectDepartureCity(String targetCity) async {
  // 跳转配置页
  await goToConfiguration();
  await tester.pumpAndSettle();

  // 定位并展开出发地下拉菜单
  final departureDropdown = find.byKey(const Key('departure_city_dropdown'));
  await tester.tap(departureDropdown);
  await tester.pumpAndSettle();

  // 选中目标城市
  final cityOption = find.text(targetCity);
  await tester.tap(cityOption);
  await tester.pumpAndSettle();

  // 验证选择结果
  expect(find.descendant(of: departureDropdown, matching: find.text(targetCity)), findsOneWidget);
}

Web 端 Selenium Python 版本

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_departure_city(driver, target_city):
    # 跳转配置页
    goToConfiguration(driver)
    wait = WebDriverWait(driver, 10)

    # 定位并展开出发地下拉菜单
    departure_dropdown = wait.until(EC.element_to_be_clickable((By.ID, 'departure_city_dropdown')))
    departure_dropdown.click()

    # 选中目标城市
    city_option = wait.until(EC.element_to_be_clickable((By.XPATH, f'//*[contains(@class,"dropdown-option") and text()="{target_city}"]')))
    city_option.click()

    # 验证选择结果
    assert target_city in departure_dropdown.text

提示:代码中的元素定位标识(key、ID、XPATH规则)需要替换为你实际项目中对应组件的属性值,避免出现定位失败的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:15:00