Twitter搜索API、Python及Json解析问题
我可以使用Python的Json库从这个地址提取信息。
http://search.twitter.com/search.json?q=%23damn&result_type=recent&rpp=1&filter:retweets
大多数时候,我使用
j =json.loads(urllib.urlopen('http://search.twitter.com/search.json?q=%23damn&result_type=recent&rpp=1&filter:retweets').read())
text = j['results'][0]['text']
id = j['results'][0]['id']
可以从结果中提取文本和ID,并把它们打印出来。 我每15秒请求一次JSON,这样就不会被Twitter的限制封锁。
不过,有时候我会遇到这样的情况。
{u'completed_in': 0.021,
u'max_id': 313306991827238912L,
u'max_id_str': u'313306991827238912',
u'next_page': u'?page=2&max_id=313306991827238912&q=%23damn&rpp=1&result_type=recent',
u'page': 1,
u'query': u'%23damn',
u'refresh_url': u'?since_id=313306991827238912&q=%23damn&result_type=recent',
u'results': [],
u'results_per_page': 1,
u'since_id': 0,
u'since_id_str': u'0'}
结果字段里面似乎什么都没有。 这就导致了下面的错误。
Traceback (most recent call last):
File "C:\Users\Home\Desktop\test.py", line 32, in <module>
text = j['results'][0]['text']
IndexError: list index out of range
这个错误会导致Python命令行关闭。 我考虑过放一个'while'循环,确保结果字段有内容再继续,但我担心这样会发送太多请求,导致脚本被Twitter锁定。
你遇到过这个问题吗?你知道怎么解决吗?
1 个回答
0
在调用结果之前,我会加一个if语句,或者用try语句。我发现使用网络API的时候,结果并不总是可靠,所以最好还是小心一点。