使用python進行新浪微博應用開發


如何在新浪開放平台上創建一個應用?
 
  1. 開放平台-我的應用下面創建新的應用。按照提示一步一步創建,傻瓜式的。                                          
  2. 點擊剛才創建的應用進入詳細頁面,然后查看應用信息-基本信息下面。在程序開發過程中,我們需要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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM