简体   繁体   English

如何用python从NBA网站上抓取统计数据

[英]How to scrape stats from NBA website with python

I am trying to scrape advanced stats from the NBA website, more specifically from this link https://stats.nba.com/leaders/?StatCategory=FG3M&PerMode=Totals .我正在尝试从 NBA 网站上抓取高级统计数据,更具体地说是从这个链接https://stats.nba.com/leaders/?StatCategory=FG3M&PerMode=Totals However, I seem to be getting the error 'NoneType' object has no attribute 'tbody'.但是,我似乎收到错误“NoneType”对象没有属性“tbody”。 I would appreciate it if someone helped me.如果有人帮助我,我将不胜感激。 Thanks.谢谢。

My code我的代码

import requests
from bs4 import BeautifulSoup
import pandas as pd

URL = 'https://stats.nba.com/leaders/?StatCategory=FG3M&PerMode=Totals'
response = requests.get(URL)
soup = BeautifulSoup(response.content, 'html.parser')

columns = ['#', 'PLAYER', 'GP', 'MIN', 'PTS', 'FGM', 'FGA', 'FG%',  '3PM', '3PA',
        '3P%', 'FTM', 'FTA', 'FT%', 'OREB', 'DREB', 'REB', 'AST', 'STL', 'BLK',
        'TOV', 'PF', 'EFF', 'AST/TOV', 'STL/TOV']

df = pd.DataFrame(columns=columns)
table = soup.find('table').tbody

trs = table.find_all('tr')
for tr in trs:
    tds = tr.find_all('td')
    row = [td.text.replace('\n', '') for td in tds]
    df = df.append(pd.Series(row, index=columns), ignore_index=True)

df.to_csv('Stats NBA.csv', index=False)
import requests
import pandas as pd

r = requests.get(
    'https://stats.nba.com/stats/leagueLeaders?LeagueID=00&PerMode=Totals&Scope=S&Season=2019-20&SeasonType=Regular+Season&StatCategory=FG3M').json()

df = pd.DataFrame(r['resultSet']['rowSet'], columns=r['resultSet']['headers'])
df.to_csv('output.csv', index=False)
print('done')

View Output Online: Click Here在线查看输出: 点击这里

API is cool usually. API通常很酷。

import requests

import pandas as pd

r = requests.get(
    'https://stats.nba.com/stats/leagueLeaders?LeagueID=00&PerMode=Totals&Scope=S&Season=2020-21&SeasonType=Regular+Season&StatCategory=FG3M').json()

df = pd.DataFrame(r['resultSet']['rowSet'], 

columns=r['resultSet']['headers'])

df.to_csv('NBA stats.csv', index=False)

print(df)

output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM