如何在新浪開放平台上建立一個應用?
- 在開放平台-我的應用程式下面建立新的應用。按照提示一步一步建立,傻瓜式的。
- 點擊剛才建立的應用進入詳細頁面,然後查看應用資訊-基本資料下面。在程式開發過程中,我們需要app key 和 app secret來調用新浪API。
3. 下載對應語言的sdk,當然這裡以python為例。:http://code.google.com/p/sinaweibopy/。下載完成後將裡面的weibo.py複製到你的應用程式同一目錄下,或者複製到lib/site-package下。這樣你的應用就可以調用sdk了。 4. 在你的程式裡面做如下測試,如果你幸運的話你應該能得到正確的返回結果了。
from weibo
import APIClient
APP_KEY = 'xxxx' # app key
APP_SECRET = 'xxxx' # app secret
CALLBACK_URL = 'xxxxxx'# callback url
#利用官方微博SDK
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
#用得到的url到新浪頁面訪問
url = client.get_authorize_url()
webbrowser.open_new(url)
#手動輸入新浪返回的code
code = raw_input()
#新浪返回的token,類似abc123xyz456,每天的token不一樣
r = client.request_access_token(code)
access_token = r.access_token
expires_in = r.expires_in # token到期的UNIX時間
#設定得到的access_token
client.set_access_token(access_token, expires_in)
#有了access_token後,可以做任何事情了
client.get.friendships__followers()
5. 利用API做你能想到的任何事情,比如我做了一個粉絲和粉絲的性別分析: 要實現這個統計很簡單,首先獲得某個使用者的所有粉絲:
def GetAllFriends(
self,uid):
"""
得到所有的關注對象
返回:(screenName,gender)元組數組
"""
resFollows = []
nextCursor = -1
while nextCursor != 0:
followers =
self.client.get.friendships__friends(uid=uid,count=200,cursor=nextCursor)
nextCursor = followers["next_cursor"]
for follower
in followers["users"]:
resFollows.append( (follower["screen_name"],follower["gender"]) )
print
len(resFollows)
return resFollows
然後利用matplotlib這個第三方庫進行繪圖即可。關於matplotlib我想我後面會寫一些文章進行說明的,很強大的一個二維繪圖庫。
def FriendsMaleOrFemale(uid):
wb = MySinaWeiBo()
m = 0
f = 0
n = 0
for i
in wb.GetAllFriends(uid):
if i[1] == "m":
m = m+1
elif i[1] == "f":
f = f+1
else:
n = n+1
ind = np.arange(1,4) # np.arange(1,N+1) # the x locations for the groups
width = 0.25 # the width of the bars
plt.subplot(111)
rects1 = plt.bar(ind, (m,f,n), width,bottom = 0,align = 'center')
#增加Y軸說明
plt.ylabel(u'關注數')
#增加標題
plt.title(u'我關注的人性別分析(有效樣本:%d)' % (m+f+n))
#設定x座標位置和文字
plt.xticks(ind, (u"男",u"女",u"未知") )
autolabel(rects1)
plt.legend(rects1,(u"使用者:%s" % wb.GetUserByUid(uid),))
plt.show()