使用python呼叫新浪微博API的小經歷
Python標準庫裡有專門處理Json的標準庫--json庫。使用的是新浪微博Python SDK。
剛開始走了很多彎路,Python SDK的介紹頁面內容有點少只是簡單的介紹瞭如何使用這個SDK用新浪微博接入,至於如何獲取使用者的資訊沒有提到。Python SDK是第三方的基於2.7的,我見過有人改寫的基於3.2的,連結忘存了。
1、新浪微博python SDK的使用
首先、需要自己申請為開發者,先建立一個一個應用,獲得AppKey和AppSecret。如圖所示:
還有要在高階資訊中設定好正確的回撥頁面,如果沒有自己的網站,最好是將回調頁面設定成新浪微博提供的:https://api.weibo.com/oauth2/default.html,如圖所示:
接下來看測試用的程式碼:
# _*_ coding: utf-8 _*_ import os import sys import weibo import webbrowser import json APP_KEY = '你的appkey' MY_APP_SECRET = '你的appsecret' REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html' #這個是設定回撥地址,必須與那個”高階資訊“裡的一致 #請求使用者授權的過程 client = weibo.APIClient(APP_KEY, MY_APP_SECRET) authorize_url = client.get_authorize_url(REDIRECT_URL) #開啟瀏覽器,需手動找到位址列中URL裡的code欄位 webbrowser.open(authorize_url) #將code欄位後的值輸入控制檯中 code = raw_input("input the code: ").strip() #獲得使用者授權 request = client.request_access_token(code, REDIRECT_URL) #儲存access_token ,exires_in, uid access_token = request.access_token expires_in = request.expires_in uid = request.uid #設定accsess_token,client可以直接呼叫API了 client.set_access_token(access_token, expires_in) #get_results = client.statuses__mentions() #get_results = client.frientdships__friends__ids() #get_results = client.statuses__user_timeline() #get_results = client.statuses__repost_timeline(id = uid) #get_results = client.search__topics(q = "笨NANA") get_results = client.statuses__friends_timeline() print "************the type of get_results is : " print type(get_results) #print get_results[0][0]['text'] get_statuses = get_results.__getattr__('statuses') print type(get_statuses) print get_statuses[0]['text'] json_obg = json.dumps(get_results) print type(json_obg) #resultsdic = json.load(json_obg) print uid # get_json = json.dumps(client.statuses__user_timeline()) #decodejson = json.loads(get_results) #print decodejson #file = open("result.txt", "w") #file.write(decodejson) #file.close() print "*************OK**********"
2、解析API返回來的Json資料
如使用新浪的這個API:statuses__friends_timeline()
以為它直接返回的資料就能用,就直接json.dumps()了,但是總是出錯,看了上面的部落格文章才想到測試下它返回的資料型別是什麼,原來自己一直認為返回的是json物件,直接使用就可以了。
get_results = client.statuses__friends_timeline()
print "************the type of get_results is : "
print type(get_results)
用這個測試發現返回的型別是<class weibo.JsonOject>這才想到了要看看weibo這個庫的的幫助文件,這個不是看它網站上給的,而是在python終端中:import weibo,然後help(weibo)中找的,找到了:
裡面給出了取出某個屬性的方法,既使用這個方法可以取出Json物件某個”鍵名“所對應的”鍵值“。其實應該想到既然返回的是一個類物件,那麼這個類肯定有對這些物件屬性的一些操作。
測試程式碼如下:
get_statuses = get_results.__getattr__('statuses')
print type(get_statuses)
print get_statuses[0]['text']
取出的屬性在python中是list型別,那麼就可以直接對list型別做一些操作了。
最終效果如入所示:
感想:學習時看相關文件、文章要沉的住氣,專心把文件看明白了,不能走馬觀花的瀏覽一下,不然弄的還是不清不楚,自己一寫就出錯,並且錯了不知道如何找原因,感覺是這樣按檔寫的啊,怎麼會錯呢,浪費時間
轉載:http://www.51bigfool.com/%e4%bd%bf%e7%94%a8python%e8%b0%83%e7%94%a8%e6%96%b0%e6%b5%aa%e5%be%ae%e5%8d%9aapi%e7%9a%84%e5%b0%8f%e7%bb%8f%e5%8e%86.html