【发布时间】:2012-10-30 23:54:38
【问题描述】:
我正在尝试使用 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 的工作原理没有完全了解。
这是来自 API 的 example page。
怎么了?
编辑 在尝试在另一个浏览器中加载示例页面后,我还看到了我在页面顶部发布的 JSON。不过,它似乎只适用于 //new.json 。如果我尝试 //hot.json 或只是 /.json,我会得到我想要的。
【问题讨论】:
-
The API link 提供给我相同的数据,
{"kind": "Listing", "data": {"modhash": "", "children": [], "after": null, "before": null}}。您确定您正确使用 API 吗? -
你确定你没有打印出你解析的 JSON 数据吗?
-
@Tim -- 这很奇怪,因为我得到了this。我不得不将限制更改为 10,因为 100 浪费太大而无法容纳馅饼。
-
@icktoofay -- 来自打印 _json。
-
@JamesBrewer:我不知道为什么,我以前没有使用过这个 API。希望其他人可以阐明它。