Python爬取球员信息生成Excel表格并进行可视化
时间: 2024-04-06 11:32:36 浏览: 14
要将爬取到的球员信息生成Excel表格并进行可视化,可以使用Python的pandas和matplotlib库。
首先,使用pandas库将爬取到的球员信息存储到DataFrame对象中,然后使用DataFrame对象的to_excel方法将数据保存到Excel文件中。
接着,使用matplotlib库中的pyplot模块绘制球员身高和体重的柱状图。
下面是一个完整的Python代码示例:
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
# 发送请求并获取网页内容
url = 'https://www.basketball-reference.com/players/a/abdelal01.html'
response = requests.get(url)
html = response.text
# 解析网页
soup = BeautifulSoup(html, 'html.parser')
name = soup.find('h1', {'itemprop': 'name'}).text
position = soup.find('span', {'itemprop': 'position'}).text
height = soup.find('span', {'itemprop': 'height'}).text
weight = soup.find('span', {'itemprop': 'weight'}).text
# 存储数据到DataFrame对象中
data = {'Name': [name], 'Position': [position], 'Height': [height], 'Weight': [weight]}
df = pd.DataFrame(data)
# 将数据保存到Excel文件中
df.to_excel('player_info.xlsx', index=False)
# 绘制身高和体重的柱状图
height = float(height.split('-')[0]) * 12 + float(height.split('-')[1])
weight = int(weight)
plt.bar(['Height', 'Weight'], [height, weight])
plt.title('Player Info')
plt.show()
```
这个示例将Abdel Nader的身高和体重存储到了DataFrame对象中,并将数据保存到了Excel文件中。然后,使用matplotlib库绘制了身高和体重的柱状图。你可以将URL更改为其他球员页面的URL以爬取其他球员的信息。