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

如何爬取网站图表数据 以Worldometers美国新冠疫情数据页为例

问题1:定位目标script标签的方法

你要爬取的三个图表都是通过Highcharts实现的,每个图表的配置数据都独立存放在单独的script标签中,你可以通过图表的唯一名称关键词来匹配对应的script,比你原有代码匹配xAxis的方式准确率更高:

  • 累计确诊对应关键词:Total Coronavirus Cases
  • 现有确诊对应关键词:Active Cases
  • 累计死亡对应关键词:Total Deaths
问题2:提取日期和对应数值的方法

目标script标签内的配置是标准的Highcharts结构:

  • 日期数据存放在xAxis.categories字段中
  • 对应数值存放在series[0].data字段中
    你可以通过正则分别提取这两个字段的内容,再解析为Python可操作的列表即可。
完整可运行代码
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import json
import re
import ast

# 配置无头Chrome
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_experimental_option('excludeSwitches', ['enable-logging'])

# 初始化驱动,若未配置chromedriver环境变量需传入executable_path参数指定路径
driver = webdriver.Chrome(options=options)
driver.get("https://www.worldometers.info/coronavirus/country/us/")
html = driver.page_source
driver.close()

soup = bs(html, "html.parser")
all_scripts = [str(i) for i in soup.find_all("script")]

# 定义三个目标图表的匹配规则
target_charts = [
    {"name": "美国累计新冠确诊病例", "keyword": "Total Coronavirus Cases"},
    {"name": "美国现有确诊病例", "keyword": "Active Cases"},
    {"name": "美国累计新冠死亡病例", "keyword": "Total Deaths"}
]

def parse_chart_data(script_content):
    # 提取日期数组
    date_raw = re.findall(r"xAxis:\s*{\s*categories:\s*(\[.*?\])", script_content, re.S)[0]
    date_list = json.loads(date_raw)
    # 提取数值数组,处理null值和语法兼容问题
    data_raw = re.findall(r"series:\s*\[\s*{\s*name:.*?data:\s*(\[.*?\])", script_content, re.S)[0]
    data_raw = data_raw.replace("null", "None")
    data_list = ast.literal_eval(data_raw)
    # 返回日期-数值配对结果
    return list(zip(date_list, data_list))

# 批量提取三个图表的数据
for chart in target_charts:
    target_script = [s for s in all_scripts if chart["keyword"] in s][0]
    result = parse_chart_data(target_script)
    print(f"\n===== {chart['name']} 数据(前5条示例)=====")
    for item in result[:5]:
        print(item)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:51:01