2017-02-24 123 views
0

我試圖爲我的智能鏡像創建一個刮刀。我已經建立了一個python腳本來獲取天氣,污染水平&新聞和我沒有得到的東西是爲什麼我在獲取這個功能塊時的錯誤,而不是像天氣&污染等級的其他功能。這是我收到錯誤的代碼:KeyError:'data in one function but not in other

def news(self): 
     reddit1 = "https://www.reddit.com/r/LifeProTips/hot.json" 
     reddit2 = "https://reddit.com/r/technology/hot.json" 
     reddit3 = "https://reddit.com/r/Futurology/hot.json" 
     reddit4 = "https://reddit.com/r/Showerthoughts/hot.json" 
     lpt = requests.get(reddit1) 
     tech = requests.get(reddit2) 
     futu = requests.get(reddit3) 
     show = requests.get(reddit4) 
     lptd = json.loads(lpt.text) 
     techd = json.loads(tech.text) 
     futud = json.loads(futu.text) 
     showd = json.loads(show.text) 
     lpttitle = lptd['data']['children'][0]['data']['title'] 
     print(lpttitle) 
     lptcontent = lptd['data']['children'][0]['data']['selftext'] 
     print(lptcontent) 
     techttitle = techd['data']['children'][0]['data']['title'] 
     print(techtitle) 
     techcontent = techd['data']['children'][0]['data']['selftext'] 
     print(techcontent) 
     fututitle = futud['data']['children'][2]['data']['title'] 
     print(fututitle) 
     futucontent = futud['data']['children'][0]['data']['selftext'] 
     print(futucontent) 
     showtitle = showd['data']['children'][0]['data']['title'] 
     print(showdata) 
     showcontent = showd['data']['children'][0]['data']['selftext'] 
     print(showcontent) 
     lptdump = requests.put('firebaseurl',json={"Title": lpttitle, "Content": lptcontent}) 
     techdump = requests.put('firebaseurl',json={"Title": techtitle, "Content": techcontent}) 
     futudump = requests.put('firebaseurl',json={"Title": fututitle, "Content": futucontent}) 
     showdump = requests.put('firebaseurl',json={"Title": showtitle, "Content": showcontent}) 

但對於這樣的功能:

def pollution(self): 
    url = "api" 
    url2 = "api" 
    pm10 = requests.get(url) 
    pm25 = requests.get(url2) 
    pm10leveldata = json.loads(pm10.text) 
    pm25leveldata = json.loads(pm25.text) 
    pm10level = pm10leveldata[0]['data'] 
    pm25level = pm25leveldata[0]['data'] 
    print pm10level 
    print pm25level 
    # pm10 = round(pm10level) 
    # pm25 = round(pm25level) 
    pdump = requests.put('firebaseurl',json={"Pm10": pm10level, "Pm25": pm25level}) 

沒有錯誤。爲什麼我在那一個但不是在這樣

+0

那一行發生錯誤? –

+0

@ColinBasnett它發生在行上:'lpttitle = lptd ['data'] ['children'] [0] ['data'] ['title']'如果我取消註釋到其他人 – MatejMecka

+1

打印出'lptd '在執行該行之前查看密鑰是否確實存在。你可能會假設數據的格式不正確。 –

回答

3

打印出來lptd功能得到一個關鍵的錯誤嘗試之前使用它:

{'error': 429, 'message': 'Too Many Requests'} 

你已經激怒了reddit的。這可能會發生在任何請求上,因此它可能會顯示爲錯誤正在跳轉。

順便說一句,你可以直接從請求得到JSON:

lptd = requests.get(reddit1).json() 
+0

感謝隊友。這是其中一個問題,需要花時間。在它周圍休息一下,不要放棄它。加上idk怎麼樣,但是當打印lptd和其他人不會崩潰 – MatejMecka

+0

我也不知道......前幾次我跑你的腳本它爲我工作,然後開始失敗。也許它跟蹤了大量的時間,它的測試運行之間的延遲會產生變化。 – tdelaney

相關問題