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

Selenium如何根据下拉框条件抓取多级联动的大洲国家城市等关联数据

Selenium三级联动下拉框全量数据爬取实现方案

核心逻辑设计(通用三级联动场景)

核心思路为从上到下逐层遍历,每次选中上层选项后等待下层下拉加载完成,再抓取下层可选值,最终按嵌套结构存储数据

  • 依赖准备:导入Selenium的Select类处理原生下拉框,导入WebDriverWait实现显式等待,避免硬编码等待时间导致的加载失败问题
  • 第一层遍历:定位最上级下拉元素,提取所有非默认提示的可选值存入列表,循环遍历每个值
  • 第二层联动:每次选中第一层的某个值后,等待第二层下拉完成加载、可选值更新,提取第二层所有可选值存入列表,循环遍历每个值
  • 第三层数据抓取:每次选中第二层的某个值后,等待第三层下拉加载完成,提取所有可选值存入数组,对应到当前的一二级选项下
  • 数据格式化:按要求的嵌套JSON结构存储所有层级的关联数据

示例代码逻辑(适配大洲-国家-城市场景)

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

driver = webdriver.Chrome()
# 访问目标页面后初始化结果数组
result = []

# 1. 提取第一层所有大洲选项,排除默认提示类空选项
continent_select = Select(driver.find_element(By.ID, "continent"))
continent_options = [opt.text.strip() for opt in continent_select.options if opt.text.strip()]

for continent in continent_options:
    # 选中当前大洲
    continent_select.select_by_visible_text(continent)
    # 等待国家下拉加载完成(判断条件为option数量大于默认提示项的1个)
    WebDriverWait(driver, 10).until(lambda d: len(Select(d.find_element(By.ID, "country")).options) > 1)
    country_select = Select(driver.find_element(By.ID, "country"))
    country_options = [opt.text.strip() for opt in country_select.options if opt.text.strip()]
    # 初始化当前大洲的数据结构
    continent_data = {continent: []}
    
    for country in country_options:
        # 选中当前国家
        country_select.select_by_visible_text(country)
        # 等待城市下拉加载完成
        WebDriverWait(driver, 10).until(lambda d: len(Select(d.find_element(By.ID, "city")).options) > 1)
        city_select = Select(driver.find_element(By.ID, "city"))
        city_list = [opt.text.strip() for opt in city_select.options if opt.text.strip()]
        # 存入当前国家对应的城市列表
        continent_data[continent].append({country: city_list})
    
    result.append(continent_data)

# 输出符合要求的JSON格式
print(json.dumps(result, ensure_ascii=False, indent=2))

注意事项

  • 如果目标网站下拉为div模拟的非原生select组件,将上述代码中Select相关操作替换为「点击下拉框触发选项展开→等待选项渲染→遍历点击对应选项」的逻辑即可
  • 遍历过程中如果出现页面刷新,要重新定位下拉元素,避免元素过期报错
  • 可添加异常捕获逻辑,跳过加载失败的选项,保证遍历流程不中断
  • 你提到的注册网站前置操作完成(选择client type = Individual并进入第三页表单)后,将上述逻辑中的三层下拉元素定位分别替换为province、district、municipality对应的元素即可,逻辑完全通用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:15:03