为此代码绘制可视化图表:import requests from bs4 import BeautifulSoup url = "https://nba.hupu.com/stats/players" response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") table = soup.find("table", {"class": "players_table"}) headers = [] rows = [] for row in table.find_all("tr"): cells = row.find_all("td") if len(cells) > 0: row_data = [] for i in range(len(cells)): if len(headers) < len(cells): headers.append(cells[i].get_text().strip()) else: row_data.append(cells[i].get_text().strip()) if len(row_data) > 0: rows.append(row_data) # 打印表头和每一行数据 print(headers) for row in rows: print(row)
时间: 2024-04-27 11:23:07 浏览: 169
好的,以下是一个使用Python的Matplotlib库绘制可视化图表的示例代码,它可以基于您提供的表格数据生成柱形图:
```python
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
url = "https://nba.hupu.com/stats/players"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
table = soup.find("table", {"class": "players_table"})
headers = []
rows = []
for row in table.find_all("tr"):
cells = row.find_all("td")
if len(cells) > 0:
row_data = []
for i in range(len(cells)):
if len(headers) < len(cells):
headers.append(cells[i].get_text().strip())
else:
row_data.append(cells[i].get_text().strip())
if len(row_data) > 0:
rows.append(row_data)
# 构建数据字典
data_dict = {}
for i in range(len(headers)):
data_dict[headers[i]] = []
for j in range(len(rows)):
data_dict[headers[i]].append(float(rows[j][i]))
# 绘制柱形图
fig, ax = plt.subplots()
for key in data_dict.keys():
ax.bar(data_dict[key], label=key, alpha=0.5)
ax.set_ylabel('数据')
ax.set_title('NBA球员数据')
ax.legend()
plt.show()
```
这段代码首先基于您提供的爬虫代码获取表格数据,并将其存储在名为“headers”和“rows”的列表中。然后,它构建了一个名为“data_dict”的数据字典,其中键为表头,值为每个球员在该列中的数据。最后,代码使用Matplotlib库绘制柱形图,将所有列的数据可视化。
您可以根据自己的需要对图表进行修改和美化,例如更改柱形图的颜色和样式,添加标题和标签等。
阅读全文