Reddit API返回无用的JSON

5 python urllib2 reddit

我正在尝试使用他们的API和Python的urllib2从Reddit中删除新故事,但我一直在获取像这样的JSON文档:

{ u'kind': u'Listing', u'data': { u'modhash': u'', u'children': [], u'after': None, u'before': None }}
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

import json
import time
import urllib2

def get_submissions(after=None):
    url = 'http://reddit.com/r/all/new.json?limit=100'
    if after:
        url += '&after=%s' % after

    _user_agent = 'Reddit Link Analysis Bot by PirateLogic @ github.com/jamesbrewer'
    _request = urllib2.Request(url, headers={'User-agent': _user_agent})
    _json = json.loads(urllib2.urlopen(_request).read())   

    return [story for story in _json['data']['children']], _json['data']['after']

if __name__ == '__main__':
    after = None
    stories = []
    limit = 1
    while len(stories) < limit:
        new_stories, after = get_submissions(after)
        stories.extend(new_stories)
        time.sleep(2) # The Reddit API allows one request every two seconds.
        print '%d stories collected so far .. sleeping for two seconds.' % len(stories)
Run Code Online (Sandbox Code Playgroud)

我已经写了非常简短,直接,但我显然忽视的东西或我没有API的一个完整的理解或者是如何工作的urllib2.

这是API 的示例页面.

这是怎么回事?

编辑尝试在另一个浏览器中加载示例页面后,我也看到了我在页面顶部发布的JSON.它似乎只适用于//new.json.如果我尝试//hot.json或只是/.json,我得到我想要的.

bbo*_*boe 3

编辑:自 2013 年 2 月 22 日起,所需的new排序不再需要sort=new添加为 URL 参数。这是因为rising排序不再是在路由下提供,而是由[ source/new ]提供。/rising


URL http://reddit.com/r/all/new.json?limit=100的问题在于new页面默认使用rising排序。如果您已登录,并且已将默认排序更改为,那么您真正看到的是页面http://reddit.com/r/all/new.json?limit=100&sort=newnew的结果。注意添加参数sort=new

因此结果是正确的,只是 /r/all 的上升视图尚未更新。

与此相关的是,如果您打算使用 API 的多个部分,我强烈建议您使用PRAW(python reddit API 包装器),而不是编写自己的代码。这是您想要的相关代码:

import praw
r = praw.Reddit('YOUR DESCRIPTIVE USER AGENT NAME')
listing = list(r.get_subreddit('all').get_new_by_date())
print listing
Run Code Online (Sandbox Code Playgroud)

如果您只想迭代提交的内容,则可以省略该list()部分。

  • 1000 项限制是 reddit 限制,而不是 PRAW 限制。唯一的例外(我知道)是上面显示的“/r/all/new?sort=new”列表。我刚刚确认使用 `r.get_subreddit('all').get_new_by_date(limit=2000)` 实际上会获取 2000 个项目。将 `limit=2000` 替换为 `limit=None` 以继续回到 reddit 的开头。 (2认同)