Python如何調用新浪api接口的問題


前言:這些天在研究如何調用新浪開放平台的api分析新浪微博用戶的數據

成果:成功調用了新浪api獲取了用戶的一些個人信息和無數條公共微博

不足:新浪開放平台訪問有限制,返回的數據着實有限,不足以分析問題,真的要分析問題還是得個人寫爬蟲

 

下面是調用新浪開放api的過程:

第一步:按這個做就行

http://www.cnblogs.com/dhsunny/p/3578399.html?utm_source=tuicool&utm_medium=referral

其中有一不那個新浪api測試工具是打不開的,要自己百度

api測試工具打開

第二步:這是是我重點介紹一步,調用新浪api怎么獲取數據,總不能在api測試工具上面弄吧,這個時候我采用的是用python

先搭建好python開發環境,具體參考:http://www.imooc.com/learn/397

個人建議在eclipse上面搭建,視頻上有教程

下面是調用新浪api的代碼:調用的接口是

statuses/public_timeline

這個接口的介紹是:http://open.weibo.com/wiki/2/statuses/public_timeline
 
代碼如下:
#coding:utf-8
from weibo import APIClient
import webbrowser
import MySQLdb
APP_KEY = '984793585' # app key
APP_SECRET = 'ab2c926021d5cfbbc75587e67bd05a8c' # app secret
CALLBACK_URL = 'http://weibo.com/muqingcai/home?wvr=5'# 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("input the code: ").strip()


#新浪返回的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后,可以做任何事情了


#print client.statuses__public_timeline()  
count = 1
s = set([('mu','basketball','guangzhou','liuchuanfen')])  
def getDataByPublic(count):
    while True:
        if count>=50:
            break
        statuses = client.statuses__public_timeline()['statuses']  
        length = len(statuses)          
        #輸出了部分信息  
        for i in range(0,length):  
            nickName = statuses[i]['user']['screen_name']  
            profile = statuses[i]['user']['description']  
            location = statuses[i]['user']['location']  
            weibo = statuses[i]['text'] 
            print u'昵稱:'+nickName
            print u'簡介:'+profile
            print u'位置:'+location  
            print u'微博:'+weibo  
        count += 1    
getDataByPublic(1)
 
說明:APP_KEY 和APP_SECRET 需要在新浪開放平台上面創建應用才能獲得,具體方法看第一步,CALLBACK_URL也要在應用信息的高級信息里面說明,這是回掉地址,就填你微博的首頁地址
 
運行上面程序:會彈出:
 

輸入你的微博賬號密碼,接着到了微博主頁

 
把code輸入到控制台按回車:
即可獲得數據,這些數據可以存在數據庫,也可以存到本地
 


免責聲明!

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



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