You need to enable JavaScript to run this app. 如何使用Selenium正确采集URL固定不变的动态网站数据?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Selenium正确采集URL固定不变的动态网站数据?

问题原因

这个站点是典型的ASP.NET WebForm应用,所有交互通过表单提交实现,页面无跳转所以URL保持不变,属于正常现象,用Selenium模拟用户操作即可完成采集。

你现有代码的错误

  1. XPath语法错误:不存在adiv标签,且class属性用了中文引号,无法匹配到对应元素
  2. 缺少等待逻辑:页面元素未加载完成就执行查找,大概率返回空列表

完整采集实现步骤

推荐用webdriver_manager自动管理ChromeDriver,避免版本不匹配问题,采集逻辑如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import pandas as pd
import time

# 初始化驱动器
driver = webdriver.Chrome()
driver.get("https://fcraonline.nic.in/fc3_amount.aspx")
wait = WebDriverWait(driver, 10)

# 存储所有数据的列表
all_data = []

# 先获取所有可选年度
year_select = Select(wait.until(EC.presence_of_element_located((By.ID, "ddlYear"))))
year_options = [option.text for option in year_select.options if option.text.strip() != "Select"]

for year in year_options:
    # 选择年度
    year_select = Select(wait.until(EC.element_to_be_clickable((By.ID, "ddlYear"))))
    year_select.select_by_visible_text(year)
    time.sleep(1) # 等待邦下拉框刷新
    
    # 获取所有可选邦
    state_select = Select(wait.until(EC.presence_of_element_located((By.ID, "ddlState"))))
    state_options = [option.text for option in state_select.options if option.text.strip() != "Select"]
    
    for state in state_options:
        # 选择邦
        state_select = Select(wait.until(EC.element_to_be_clickable((By.ID, "ddlState"))))
        state_select.select_by_visible_text(state)
        time.sleep(1) # 等待查询按钮可用
        
        # 点击查询按钮
        wait.until(EC.element_to_be_clickable((By.ID, "btnSearch"))).click()
        # 等待表格加载完成
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "table#gvDetails")))
        
        # 解析表格数据
        soup = BeautifulSoup(driver.page_source, "lxml")
        table = soup.find("table", {"id": "gvDetails"})
        df = pd.read_html(str(table))[0]
        # 补充年度和邦字段
        df["年度"] = year
        df["邦"] = state
        all_data.append(df)
        
        # 可选:打印进度
        print(f"已完成采集:{year}年-{state}")

# 合并所有数据导出
final_df = pd.concat(all_data, ignore_index=True)
final_df.to_excel("fcra_data.xlsx", index=False)

driver.quit()

注意事项

  • 如果频繁采集被拦截,可以加更长的随机延迟,或者配置浏览器代理
  • 代码里的元素ID都是从站点实际DOM里提取的,如果站点更新DOM结构,对应修改ID即可
  • 如果不需要采集所有年度和邦,可以自行裁剪year_options和state_options列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 20:36:06