简体   繁体   English

如何从stats.nba.com API获取JSON响应?

[英]How to obtain a JSON response from the stats.nba.com API?

I'm just trying to simply use a Python get request to access JSON data from stats.nba.com. 我只是想简单地使用Python get请求从stats.nba.com访问JSON数据。 It seems pretty straight-forward as I can enter the URL into your browser and get the results I'm looking for. 看起来很简单,因为我可以在浏览器中输入URL并获得所需的结果。 However, whenever I run this the program just runs to no end. 但是,每当我运行此程序时,该程序将一直运行。 I'm wondering if I have to include some type of headers information in my get request. 我想知道是否必须在我的get请求中包括某种类型的标头信息。

The code is below: 代码如下:

import requests

url = 'http://stats.nba.com/stats/commonteamroster?LeagueID=00&Season=2017-18&TeamID=1610612756'
response=requests.get(url)
print response.text

I have tried to visit the url you given, you can add header to your request to avoid this problem (the minimum information you need to provide is User-Agent, I think you can use more header information as you can): 我尝试访问您提供的url ,可以将标头添加到您的请求中以避免此问题(您需要提供的最低限度信息是User-Agent,我认为您可以使用更多标头信息):

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
response = requests.get(url, headers=headers)

The stats.nba.com website need your 'User-Agent' header information. stats.nba.com网站需要您的“用户代理”标头信息。

You can get your request header information from Network tab in the browser. 您可以从浏览器的“网络”选项卡中获取请求标头信息。

Take chrome as example, when you press F12 , and visit url you given, you can find the relative request information, the most useful information is request headers. 以chrome为例,当您按F12键并访问给定的url时,您可以找到相对的请求信息,其中最有用的信息是请求标头。

在此处输入图片说明

You need to use headers. 您需要使用标题。 Try copying from your browser's network tab. 尝试从浏览器的“网络”标签进行复制。 Here's what worked for me: 这对我有用:

request_headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive',
    'Host': 'stats.nba.com',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
}

And here's the modified get : 这是修改后的get

response = requests.get(url, headers = request_headers)

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

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