gpt4 book ai didi

python - 我怎样才能使用 Python 从 https 链接获取 JSON?

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:27 24 4
gpt4 key购买 nike

我正在学习 Python,我想开始使用 Twitter 的流式 API。我知道如何构建一个非常基本的应用程序,该应用程序使用 urllib2 读取页面的内容,并且在过去已经成功地做到了这一点。但是,此特定 Twitter 流 API 所需的安全连接 https:// 似乎不适用于 urllib2。

我尝试从以下链接获取 JSON:https://stream.twitter.com/1.1/statuses/filter.json?locations=-122.75,36.8,-121.75,37.8

通过编写以下内容:

import urllib2
url = "https://stream.twitter.com/1.1/statuses/filter.json?locations=-122.75,36.8,-121.75,37.8"
print urllib2.urlopen(url).read()

不过,回溯说我没有被授权;我推测这是因为 HTTPS SSL 连接,研究支持这一点。所以我想我的问题是从需要这种 SSL 连接的链接获取 JSON 的最佳方法是什么?我也尝试了 curl,但再次出现错误 401。

以下是完整的回溯。

Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 438, in error File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 521, in http_error_default urllib2.HTTPError: HTTP Error 401: Unauthorized

非常感谢。

最佳答案

正如其他人提到的,您需要授权。方法如下:

参见 Twitter API with urllib2 in python

import urllib2
import base64

request = urllib2.Request( 'https://stream.twitter.com...' )
request.add_header( 'Authorization', 'Basic ' + base64.b64encode( username + ':' + password ) )
response = urllib2.urlopen( request )

关于python - 我怎样才能使用 Python 从 https 链接获取 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13355778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com