爬取虎扑球员历史数据代码
时间: 2023-09-25 16:12:36 浏览: 55
以下是爬取虎扑网站球员历史数据的示例代码,以爬取莱昂纳多·梅西(Lionel Messi)的历史数据为例:
```python
import requests
from bs4 import BeautifulSoup
# 设置要爬取的球员ID
player_id = 2
# 构造请求URL
url = f'https://nba.hupu.com/stats/players/season/{player_id}-1.html'
# 发送请求,获取HTML数据
response = requests.get(url)
html = response.text
# 使用BeautifulSoup解析HTML数据
soup = BeautifulSoup(html, 'html.parser')
# 获取表格中的所有行
rows = soup.select('#mytable tr')
# 遍历每一行,提取数据
for row in rows[1:]:
# 获取每一行中的所有单元格
cells = row.select('td')
# 提取数据
season = cells[0].text.strip() # 赛季
team = cells[1].text.strip() # 球队
gp = cells[2].text.strip() # 出场次数
gs = cells[3].text.strip() # 先发次数
min = cells[4].text.strip() # 平均时间
fg = cells[5].text.strip() # 投篮命中数
fga = cells[6].text.strip() # 投篮出手数
fg_pct = cells[7].text.strip() # 投篮命中率
three_pt = cells[8].text.strip() # 三分命中数
three_pta = cells[9].text.strip() # 三分出手数
three_pt_pct = cells[10].text.strip() # 三分命中率
ft = cells[11].text.strip() # 罚球命中数
fta = cells[12].text.strip() # 罚球出手数
ft_pct = cells[13].text.strip() # 罚球命中率
orb = cells[14].text.strip() # 进攻篮板数
drb = cells[15].text.strip() # 防守篮板数
trb = cells[16].text.strip() # 总篮板数
ast = cells[17].text.strip() # 助攻数
stl = cells[18].text.strip() # 抢断数
blk = cells[19].text.strip() # 盖帽数
tov = cells[20].text.strip() # 失误数
pf = cells[21].text.strip() # 犯规数
pts = cells[22].text.strip() # 得分数
# 打印结果
print(season, team, gp, gs, min, fg, fga, fg_pct, three_pt, three_pta, three_pt_pct, ft, fta, ft_pct, orb, drb, trb, ast, stl, blk, tov, pf, pts)
```
需要注意的是,该代码仅适用于爬取单个球员的历史数据。如果需要批量爬取多个球员的数据,可以通过循环遍历不同的球员ID来实现。此外,为了避免对虎扑网站服务器造成过大的负担,建议在爬取数据时添加适当的延时。