我嘗試使用包含在tweet文本中的指定關鍵字來查詢指定用戶的推文。這裏是我的代碼:使用Python和Tweepy查詢Twitter狀態
# Import Tweepy, sleep, credentials.py
import tweepy
from time import sleep
from credentials import *
# Access and authorize our Twitter credentials from credentials.py
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
SCREEN_NAME = "BachelorABC"
KEYWORD = "TheBachelor"
def twtr2():
raw_tweets = tweepy.Cursor(api.search, q=KEYWORD, lang="en").items(50)
for tweet in raw_tweets:
if tweet['user']['screen_name'] == SCREEN_NAME:
print tweet
twtr2()
我得到如下錯誤信息:
Traceback (most recent call last):
File "test2.py", line 19, in <module>
twtr2()
File "test2.py", line 17, in twtr2
if tweet['user']['screen_name'] == SCREEN_NAME:
TypeError: 'Status' object has no attribute '__getitem__'
我GOOGLE了很多,想,也許我需要保存Twitter的JSON在Python第一,所以我嘗試以下:
import tweepy, json
from time import sleep
from credentials import *
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
SCREEN_NAME = "BachelorABC"
KEYWORD = "TheBachelor"
raw_tweets = tweepy.Cursor(api.search, q=KEYWORD, lang="en").items(50)
for tweet in raw_tweets:
load_tweet = json.loads(tweet)
if load_tweet['user']['screen_name'] == SCREEN_NAME:
print tweet
但是,結果是可悲的:
Traceback (most recent call last):
File "test2.py", line 35, in <module>
load_tweet = json.loads(tweet)
File "C:\Python27\lib\json\__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
有人知道我的代碼有什麼問題嗎?你能幫我解決它嗎?
提前致謝!
感謝您的時間@ethanchewy我正在尋找帶有**指定** screen_name和關鍵字的推文。一般來說,你的回答是關於前20條推文。你有什麼想法找到這些條件的推文嗎? – Counter10000
@LinguisticsStudent看看位於這裏的最後一個代碼片段:https://github.com/tweepy/tweepy/blob/master/docs/code_snippet.rst。您可以將screen_names存儲在列表中,然後在該列表中搜索某個screen_name。 請注意,Twitter對查詢有嚴格的限制。 – ethanchewy
謝謝@ethanchewy。上面引用的頁面是從追隨者或用戶檢索screen_name,而不是狀態。如果我稍後再找到答案,我會更新。 – Counter10000