无法通过 Python 请求获取整个页面

Unable to GET entire page with Python request

我正在尝试从网页中获取较长的 JSON 响应(~75 MB),但我只能收到前 25 MB 左右的响应。

我用过urllib2 and python-requests but neither work. I've tried reading parts in separately and streaming the data,但这也不行。

可在此处找到数据示例:

http://waterservices.usgs.gov/nwis/iv/?site=14377100&format=json&parameterCd=00060&period=P260W

我的代码如下:

r = requests.get("http://waterservices.usgs.gov/nwis/iv/?site=14377100&format=json&parameterCd=00060&period=P260W")

usgs_data = r.json() # script breaks here

# Save Longitude and Latitude of river
latitude = usgs_data["value"]["timeSeries"][0]["sourceInfo"]["geoLocation"]["geogLocation"]["latitude"]
longitude = usgs_data["value"]["timeSeries"][0]["sourceInfo"]["geoLocation"]["geogLocation"]["longitude"]

# dictionary of all past river flows in cubic feet per second
river_history = usgs_data['value']['timeSeries'][0]['values'][0]['value']

它中断:

ValueError: Expecting object: line 1 column 13466329 (char 13466328)

当脚本尝试解码 JSON(即 usgs_data = r.json())时。

这是因为尚未收到完整数据,因此不是有效的 JSON 对象。

问题似乎是服务器一次无法提供超过 13MB 的数据。

我已经尝试过 URL 使用许多 HTTP 客户端,包括 curlwget,所有这些都以大约 13MB 的速度爆炸。我也试过启用 gzip 压缩(你也应该这样做),但解压后结果仍然被截断为 13MB。

您请求的数据过多,因为 period=P260W 指定了 260 周。如果您尝试设置 period=P52W,您应该会发现您能够检索到有效的 JSON 响应。

要减少传输的数据量,请像这样设置 Accept-Encoding header:

url = 'http://waterservices.usgs.gov/nwis/iv/'
params = {'site': 11527000, 'format': 'json', 'parameterCd': '00060', 'period': 'P52W'}
r = requests.get(url, headers={'Accept-Encoding': 'gzip,deflate'})