2016-12-05 190 views
0

嘿我的代碼當前正在將實時推文發送到數據庫。代碼會運行一段時間,5-10分鐘,但是;它最終給我下面的錯誤並退出:Tweepy JSON:'NoneType'對象沒有屬性'__getitem__'

文件 「twittergeo.py」,線路198,在

文件 「/Library/Python/2.7/site-packages/tweepy/streaming.py」第445行,在過濾器中 self._start(異步) 文件「/ Library /Python/2.7/site-packages/tweepy/streaming.py」,行361,in _start self._run() 文件「/ Library/Python/2.7/site-packages/tweepy/streaming.py「,第294行,在_run 引發異常 TypeError:'NoneType'對象沒有屬性'getitem'

from tweepy import Stream 
from tweepy import OAuthHandler 
from tweepy.streaming import StreamListener 
import json 
import MySQLdb 

canada =[-141.0,41.7,-51.0,83.7] 

consumer_key = '????????????' 
consumer_secret = '??????????????' 
access_token = '????????????????????????' 
access_secret = '??????????????' 

class TweetListener(StreamListener): 




    def on_data(self, data): 
     alldata = json.loads(data) 
     newdata = json.dumps(data) 

     created_at =  alldata["created_at"] #primary key 
     tweetId =   alldata["id"] 
     text =    alldata["text"]#must be above the dictlists 

     userId =   alldata["user"]["id"] #primarykey 
     twitterHandle =  alldata["user"]["screen_name"] 
     name =    alldata["user"]["name"] 
     location =   alldata["user"]["location"] 
     url =    alldata["user"]["url"] 
     bio =    alldata["user"]["description"] 
     protected =   alldata["user"]["protected"] 
     followers_count = alldata["user"]["followers_count"] 
     friends_count =  alldata["user"]["friends_count"] 
     geo_enabeled =  alldata["user"]["geo_enabled"] 
     lang =    alldata["user"]["lang"] 
     profile_image_url = alldata["user"]["profile_image_url"] 

     placeId =   alldata["place"]["id"]#primarykey 
     cityName =   alldata["place"]["name"] 
     fullName =   alldata["place"]["full_name"] 
     country_code =  alldata["place"]["country_code"] 
     country =   alldata["place"]["country"] 
     bounding_box =  alldata["place"]["bounding_box"] #bug 

     hashtags =   alldata["entities"]["hashtags"] #bug 
     user_mentions =  alldata["entities"]["user_mentions"] 

    return True 

    def on_error(self, status): 

auth = OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_secret) 

stream = Stream(auth, TweetListener()) 
stream.filter(locations=canada) 

Iv通過StackOverflow查看並嘗試了一些解決方案,但是;似乎沒有任何工作。

回答

2

嗯,我要去假設線198

bounding_box =  alldata["place"]["bounding_box"] #bug 

,或者試圖任何線路從字典alldata「獲得的項目」。

錯誤TypeError: 'NoneType' object has no attribute 'getitem'意味着您正試圖訪問NoneType對象。你的代碼在幾分鐘後崩潰的原因可能是你正在做的許多請求之一是返回一個空的或部分空的字典。

這是因爲如果你想做到這一點...

alldata = None 
bounding_box = alldata["place"]["whatever"] 

爲了解決這個問題,我會把周圍on_data一個巨大的try-catch塊這樣

try: 
    res = on_data(data) 
except Exception as e: 
    print(e) # Just for debuggin purposes 
+0

感謝等。該錯誤是由於我的程序如何處理bounding_box變量。有時JSON數據不會有變量bounding_box .. –

相關問題