Reddit API 返回无用的 JSON

2024-05-16

我正在尝试使用 Reddit 的 API 和 Python 的 urllib2 从 Reddit 抓取新故事,但我不断收到如下 JSON 文档:

{ u'kind': u'Listing', u'data': { u'modhash': u'', u'children': [], u'after': None, u'before': None }}

这是我的代码:

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)

我写的内容相当简短直接,但我显然忽略了一些东西,或者我没有完全理解 API 或 urllib2 的工作原理。

这是一个示例页面 http://www.reddit.com/r/all/new.json?limit=100来自 API。

这是怎么回事?

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


Edit:截至 2013 年 2 月 22 日,期望的new排序不再需要sort=new作为 URL 参数添加。这是因为rising下不再提供排序/new路线,但由提供/rising [source http://www.reddit.com/r/changelog/comments/191ngp/reddit_change_rising_is_now_its_own_tab_instead/].


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

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

在相关说明中,我强烈建议使用PRAW https://github.com/praw-dev/praw/wiki(python reddit API 包装器)如果您计划使用 API 的多个部分,而不是编写自己的代码。这是您想要的相关代码:

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

如果您只想迭代提交,您可以省略list() part.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Reddit API 返回无用的 JSON 的相关文章

随机推荐