import requests url = "https://www.bitpush.news/covid19/" # 设置请求头信息 headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36" } # 使用reqeusts模快发起 GET 请求 response = requests.get(url, headers=headers) # 获取请求的返回结果 html = response.text html # 导入 lxml from lxml import etree # 若是本地没有安装 lxml 的同学可以通过“pip install lxml”来安装 # 创建一个 lxml 对象,编码方式设为 utf-8 parse = etree.HTMLParser(encoding='utf-8') # 添加编码 # 解析 requests 返回的响应结果 doc = etree.HTML(html) country = doc.xpath('//div[@class="table_container"]//tbody/tr/td/span/text()') # 确诊人数 person = doc.xpath('//div[@class="table_container"]//tbody/tr/td[2]/text()') # 由于确诊人数中有逗号,我们使用列表推导式删除 person = [x.replace(",", "") for x in person] # 死亡人数 death = doc.xpath('//div[@class="table_container"]//tbody/tr/td[3]/text()') # 同样使用列表推导式删除逗号 death = [x.replace(",", "") for x in death] message = list(zip(country, person, death)) message import csv with open("content.csv", "w") as f: w = csv.writer(f) w.writerows(message) import pandas as pd # 读取数据 df = pd.read_csv("content.csv", names=["country", "person", "death"],encoding='gbk') df.head() df.info() df1 = df.drop(0).tail(58) df2=df1.head(15) print(df2) import matplotlib.pyplot as plt # 在jupyter中直接展示图像 %matplotlib inline # 设置中文显示 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['figure.figsize'] = (10, 5) # 设置figure_size尺寸 # x轴坐标 x = df2["country"].values # y轴坐标 y = df2["death"].values # 绘制柱状图 plt.bar(x, y) # 设置x轴名称 plt.xlabel("国家",fontsize=14) # 设置x轴名称 plt.ylabel("死亡人数",fontsize=14) plt.show()