如何解决Worldometer数据绘图时ValueError:x与y第一维度不一致报错
错误原因
- 你通过切片获取的
x是未拆分的长字符串,matplotlib会将其识别为1个独立的x轴值,对应维度为(1,) - 你生成的y轴列表长度等于字符串
x的字符总数(8000),两者长度不一致,触发维度不匹配报错。
另外你使用的硬编码偏移量切片方式非常不稳定,只要网站的JS代码稍有变动,提取的内容就会出错。
修复方案
先将JS格式的日期字符串解析为Python列表,再生成对应长度的y轴数据,同时用字符串定位的方式替换硬编码切片,提升兼容性。
完整可运行代码
import tkinter as tk from tkinter import ttk from bs4 import BeautifulSoup import requests import matplotlib.pyplot as plt root = tk.Tk() URL = "https://www.worldometers.info/coronavirus/country/us/" page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") results = soup.find_all("div", {"class": "col-md-12"}) data = results[4] script = data.find('script') stringCon = script.string # 定位日期数组的位置,替代硬编码切片 start_idx = stringCon.find('categories: [') + len('categories: [') end_idx = stringCon.find(']', start_idx) date_raw_str = stringCon[start_idx:end_idx] # 解析为日期列表 x = [item.strip().strip("'\"") for item in date_raw_str.split(',') if item.strip()] # 生成和x长度一致的y轴测试数据,你可以后续替换为真实的病例数据 y = list(range(1, len(x)+1)) plt.style.use('seaborn-dark') plt.plot(x, y, label = "US") plt.title('Daily Cases') plt.xlabel('Date') plt.ylabel('Cases') # 日期太多的话可以旋转x轴标签避免重叠 plt.xticks(rotation=45, ha='right') plt.grid(True) plt.legend() plt.tight_layout() # 调整布局避免标签被截断 plt.show() root.mainloop()
提示:如果需要获取真实的病例数作为y轴数据,可以用同样的字符串定位方式,查找JS代码中
data: [对应的数组,用相同的逻辑解析即可。
内容的提问来源于stack exchange,提问作者Teerath
相关产品推荐
相关产品推荐

