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

使用Selenium+BeautifulSoup爬取CVM站点仅返回JS无表格数据如何解决

爬虫获取目标站点表格数据的解决方案

问题原因

  • 你使用的PhantomJS已经停止维护多年,对当前主流前端JS语法兼容性极差,无法正常执行站点的动态渲染逻辑,所以只能拿到未执行JS的原始代码
  • 目标站点为ASP.NET WebForm架构,表格数据不会在页面首次加载时生成,需要主动触发查询操作后才会返回并渲染表格内容
  • 旧版本PhantomJS的浏览器特征极易被站点反爬机制识别,触发拦截规则

修复方案

推荐替换为Selenium + Chrome无头模式实现采集,同时添加动态等待和查询触发逻辑,操作步骤如下:

  1. 安装依赖包
    执行命令:pip install selenium webdriver-manager beautifulsoup4 lxml
  2. 调整后的代码
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# Chrome无头模式配置,隐藏自动化特征
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)

url = "https://www.rad.cvm.gov.br/ENET/frmConsultaExternaCVM.aspx"
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
# 抹除webdriver特征
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")

driver.get(url)
wait = WebDriverWait(driver, 15)

# 触发查询操作,可根据需求调整查询条件后再点击查询按钮
search_btn = wait.until(EC.element_to_be_clickable((By.ID, "btnConsulta")))
search_btn.click()

# 等待表格渲染完成
wait.until(EC.presence_of_element_located((By.ID, "dgDocumentos")))

html = driver.page_source
bs = BeautifulSoup(html, 'lxml')
# 提取目标表格
target_table = bs.find("table", id="dgDocumentos")
print(target_table.prettify())

driver.quit()

优化建议

  • 可根据实际采集需求调整查询条件,比如指定公司、日期范围后再触发查询,获取精准数据
  • 高频采集时可添加随机延迟,避免触发站点频率限制
  • 也可直接通过Selenium定位表格行、列元素提取数据,无需转BeautifulSoup处理,降低性能损耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:12:02