【问题标题】:Reading an HTTP stream in python在 python 中读取 HTTP 流
【发布时间】:2012-08-07 03:47:27
【问题描述】:

我正在尝试读取 Twitter 流 API 的输出,但遇到了一些问题。到目前为止,这是我的代码:

from urllib2 import *
import StringIO

password_mgr = HTTPPasswordMgrWithDefaultRealm()
url = "https://stream.twitter.com/1/statuses/sample.json"
password_mgr.add_password(None, url, 'myusername', 'mypassword')
h = HTTPBasicAuthHandler(password_mgr)
opener = build_opener(h)
page = opener.open(url)
io = StringIO(page.read())
print io.getvalue()
io.close()

我最初只使用page.read(),但导致我的控制台一直打印出流并且不会返回到代码。我现在正在尝试使用 StringIO 像流一样处理它并逐步打印出来,但是当我这样做时,我什么也得不到,而且这个过程就成立了。有没有更好的方法来做到这一点?

【问题讨论】:

标签: python twitter


【解决方案1】:

我听说了 requests 模块的好消息:

https://2.python-requests.org/en/master/user/advanced/#id9

【讨论】:

    【解决方案2】:

    请阅读流请求¶

    https://requests.kennethreitz.org/en/master/user/advanced/#streaming-requests

    import json
    import requests
    
    r = requests.get('https://httpbin.org/stream/20', stream=True)
    
    if r.encoding is None:
        r.encoding = 'utf-8'
    
    for line in r.iter_lines(decode_unicode=True):
        if line:
            print(json.loads(line))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2014-11-25
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 2016-01-11
      相关资源
      最近更新 更多