获取Tweepy搜索结果为JSON格式
我想用Tweepy从Twitter获取搜索结果,并且希望结果是JSON格式的。之前我看到这里说我需要在Tweepy的代码里添加一个类,才能实现这个功能。
但是当我查看Tweepy的代码时,我看到的是这个:
class JSONParser(Parser):
payload_format = 'json'
def __init__(self):
self.json_lib = import_simplejson()
def parse(self, method, payload):
try:
json = self.json_lib.loads(payload)
except Exception, e:
raise TweepError('Failed to parse JSON payload: %s' % e)
needsCursors = method.parameters.has_key('cursor')
if needsCursors and isinstance(json, dict) and 'previous_cursor' in json and 'next_cursor' in json:
cursors = json['previous_cursor'], json['next_cursor']
return json, cursors
else:
return json
def parse_error(self, payload):
error = self.json_lib.loads(payload)
if error.has_key('error'):
return error['error']
else:
return error['errors']
所以我并不需要去修改它的代码,因为这个功能已经存在了。
这是我的代码:
from tweepy.parsers import JSONParser
for tweet in tweepy.Cursor(api.search,
q=hashtag,
include_entities=True,
rpp=100,
parser=tweepy.parsers.JSONParser()
).items(limit):
这是我遇到的错误:
print (json.dumps(tweet))
File "/usr/lib/python2.7/json/__init__.py", line 243, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <tweepy.models.Status object at 0xb6df2fcc> is not JSON serializable
我应该从这个错误中理解什么呢?我该如何解决这个问题?
3 个回答
1
从 Tweepy 4.0(Twitter API 2)开始,你在启动客户端的时候,可以指定结果的类型。
client = tweepy.Client(bearer_token, return_type=dict)
response = client.search_recent_tweets(search_text)
isinstance(response, dict) # True
7
如果你可以不使用光标(Cursor)来工作,可以考虑用JSONParser。不过如果你能处理分页的话,可以这样做:
>>> api = tweepy.API(auth, parser=tweepy.parsers.JSONParser())
记得把rpp改成count,因为在Twitter搜索API中,rpp已经过时了。
>>> results = api.search(q="IPython", count=100)
你会得到原始格式的结果。这意味着你会得到一个字典,里面有两个键。
>>> results.keys()
[u'search_metadata', u'statuses']
你可以从“statuses”的值中获取你的搜索结果。
>>> results["statuses"]
[{u'contributors': None,
u'coordinates': None,
u'created_at': u'Wed Oct 15 03:36:08 +0000 2014',
....
8
如果你像这样使用光标
import json
api = tweepy.API(auth)
max_tweets=100
query='Ipython'
searched_tweets = [status._json for status in tweepy.Cursor(api.search, q=query).items(max_tweets)]
json_strings = [json.dumps(json_obj) for json_obj in searched_tweets]
searched_tweets
是一个包含多个 JSON 对象的列表,而 json_strings
是一个包含多个 JSON 字符串的列表。