我一直在尝试使用Python请求使用Twitter Streaming API。
文档中有simple example:
import requests
import json
r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
data={'track': 'requests'}, auth=('username', 'password'))
for line in r.iter_lines():
if line: # filter out keep-alive new lines
print json.loads(line)
[执行此操作时,对requests.post()
的调用再也不会返回。我已经进行了实验,并证明它确实可以连接到Twitter并从API接收数据。但是,它没有返回响应对象,而是坐在那里,消耗着Twitter发送的数据。从上面的代码来看,我希望requests.post()
返回一个响应对象,该对象具有到Twitter的开放连接,我可以继续接收实时结果。
文档未提及在使用所有提供的数据之前导致r.content
返回所需的任何其他步骤。其他人似乎在使用类似的代码而没有遇到此问题,例如requests.post
。
我正在使用:
注意,自请求1.x起,该参数已重命名,现在您使用r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
data={'track': 'requests'}, auth=('username', 'password'),
prefetch=False)
for line in r.iter_lines():
if line: # filter out keep-alive new lines
print json.loads(line)
:
我只需要在stream=True
上添加一个r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
data={'track': 'requests'}, auth=('username', 'password'),
stream=True)
for line in r.iter_lines():
if line: # filter out keep-alive new lines
print json.loads(line)
kwarg。