我正在尝试使用Python从NBA.com抓取数据,但在运行我的代码后等待合理的时间后我没有收到回复(如下所示)。
import requests
import json
url_front = 'http://stats.nba.com/stats/leaguedashplayerstats?College=&' + \
'Conference=&Country=&DateFrom=&DateTo=&Division=&DraftPick=&' + \
'DraftYear=&GameScope=&GameSegment=&Height=&LastNGames=0&LeagueID=00&' + \
'Location=&MeasureType='
url_back = '&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&' + \
'PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&' + \
'PlusMinus=N&Rank=N&Season=2016-17&SeasonSegment=&' + \
'SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&' + \
'VsConference=&VsDivision=&Weight='
#measure_type = ['Base','Advanced','Misc','Scoring','Opponent','Usage','Defense']
measure_type = 'Base'
address = url_front + measure_type + url_back
# Request the URL, then parse the JSON.
response = requests.get(address)
response.raise_for_status() # Raise exception if invalid response.
data = response.json() # JSON decoding.
到目前为止,我尝试重现博客帖子(here)中的代码和/或在此网站上发布的问题(Python,R),但这些代码性质相似,但我每次都得到相同的结果 - 代码实际上没有成功从URL中提取任何内容。
由于我不熟悉网络抓取,我希望能够帮助解决问题 - 对于有客户端渲染的网站(NBA.com)来说这是常见的,还是表明我的代码/计算机存在问题?在任何一种情况下,是否有共同的解决方法/解决方案?
答案 0 :(得分:0)
如果您访问浏览器中的链接,您会发现它工作正常。原因是浏览器和requests
具有不同的用户代理标头,并且该网站专门阻止看起来不像来自浏览器的HTTP请求,因为它们不希望被删除。你可以这样绕过这个:
response = requests.get(address, headers={
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0',
})
请记住这一点,不要让服务器过载。