如何爬取网站图表数据 以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
相关产品推荐
相关产品推荐

