现在status.text这一行得到的是微博文字,但是是截断的(不是完整的微博文字)。在获取微博信息时,如何通过使用on status获取微博全文?
def on_status(self, status):
if not hasattr(status,'retweeted_status'):
#db = DatabaseInteractor.DatabaseInteractor()
text=self.parse_text(status.text)
created_at=self.parse_text(status.created_at)
user_id=self.parse_text(status.user.id_str)
username=self.parse_text(status.user.name)
location=self.parse_text(status.user.location)
coordinates=self.parse_text(status.coordinates)
tweet_id=self.parse_text(status.id_str)
hashtags=self.parse_text(status.entities['hashtags'])
print("Created At: " + created_at)
print("Tweet Text: " + text)
print("Tweet ID: " + tweet_id)
print("Username: " + username)
print("Username ID: " + user_id)
print("Location: " + location )
print("Coordinates: " + coordinates)
print("Hashtags: " + hashtags)
看起来你使用的是Twitter流媒体API (statuses/filter
或a StreamListener
在tweepy中)。)
在这种情况下,如果一个Tweet有一个字段,上面写着 truncated: true
你需要在Tweet对象中寻找一个额外的字段,叫做 extended_tweet
的字段,其中将包含一个名为 full_text
.
该 tweet_mode='extended'
参数在前一个答案中建议的是在流媒体API中无效。
在Twitter开发者实验室(目前正在测试的下一版本API)中,不再区分截断或扩展的Tweets,所有的Tweet对象将返回全文数据。
如果你想在Twitter响应中获得全文,你需要在调用API时添加关键字tweet_mode='extended',像这样。
api.search(q='<something to search keyword>', tweet_mode='extended')
通过添加这个关键字,你可以从API的响应中获得全文字段,而不是文本字段,同时注意一些推文可能没有扩展文本,并会给出一个错误,所以使用 try and except
def on_status(self, status):
if not hasattr(status,'retweeted_status'):
#db = DatabaseInteractor.DatabaseInteractor()
try:
text=self.parse_text(status.retweeted_status.extended_tweet['full_text']) #Replace text with extended_tweet['full_text']
except:
text=self.parse_text(status.retweeted_status.text)
created_at=self.parse_text(status.created_at)
user_id=self.parse_text(status.user.id_str)
username=self.parse_text(status.user.name)
location=self.parse_text(status.user.location)
coordinates=self.parse_text(status.coordinates)
tweet_id=self.parse_text(status.id_str)
hashtags=self.parse_text(status.entities['hashtags'])
print("Created At: " + created_at)
print("Tweet Text: " + text)
print("Tweet ID: " + tweet_id)
print("Username: " + username)
print("Username ID: " + user_id)
print("Location: " + location )
print("Coordinates: " + coordinates)
print("Hashtags: " + hashtags)