一:獲取app-key 和 app-secret
? ? 使用自己的微博賬號登錄微博開放平臺(http://open.weibo.com/),在微博開放中心下“創建應用”創建一個應用,應用信息那些隨便填,填寫完畢后,不需要提交審核,需要的只是那個app-key和app-secret
二:設置授權回調頁
? ? 在“微博開放平臺”的“管理中心”找到剛才創建的應用,點開這個應用,點開左邊“應用信息”欄,會看見“App key”和“App Secret”的字樣,這兩個東西是要在后面程序中使用的。然后在“應用信息”下的“高級信息”點擊“編輯”按鈕,將“授權回調頁面”設置為:https://api.weibo.com/oauth2/default.html,將“取消授權回調頁”也設置為:https://api.weibo.com/oauth2/default.html。
三:安裝微博 python SDK
有兩種安裝方式:
1:http://github.liaoxuefeng.com/sinaweibopy/下載新浪微博SDK
2:python有個簡單的安裝方式:直接在命令行下鍵入:
sudo pip install sinaweibopy
四:實例驗證,獲取當前登錄用戶及其所關注(授權)用戶的最新微博
這里需要注意的是在瀏覽器彈出一個頁面,要先點擊“授權”(這里進行的OAuth 2認證,我理解為就是用戶訪問我的應用后將頁面導向新浪服務器然后用戶輸入信息到新浪服務器后授權給我的應用訪問用戶數據,這里我將的微博授權給下面的程序了),授權后瀏覽器中的URL類似:https://api.weibo.com/oauth2/default.html?code=2024222384d5dc88316d21675259d73a將code后面那個復制到控制端,程序需要讀入2024222384d5dc88316d21675259d73a這個數據?
注意:如果想獲取別的信息,只需修改
statuses = client.statuses__friends_timeline()['statuses']
中的 statuses__friends_timeline即可
# -*- coding: utf-8 -*-
from weibo import APIClient
import webbrowser #python內置的包APP_KEY = 'xxxxxxxx'#注意替換這里為自己申請的App信息
APP_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'#回調授權頁面#利用官方微博SDK
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
#得到授權頁面的url,利用webbrowser打開這個url
url = client.get_authorize_url()
print url
webbrowser.open_new(url)#獲取code=后面的內容
print '輸入url中code后面的內容后按回車鍵:'
code = raw_input()
#code = your.web.framework.request.get('code')
#client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
r = client.request_access_token(code)
access_token = r.access_token # 新浪返回的token,類似abc123xyz456
expires_in = r.expires_in# 設置得到的access_token
client.set_access_token(access_token, expires_in)#可以打印下看看里面都有什么東西
statuses = client.statuses__friends_timeline()['statuses'] #獲取當前登錄用戶以及所關注用戶(已授權)的微博</span>length = len(statuses)
print length
#輸出了部分信息
for i in range(0,length):print u'昵稱:'+statuses[i]['user']['screen_name']print u'簡介:'+statuses[i]['user']['description']print u'位置:'+statuses[i]['user']['location']print u'微博:'+statuses[i]['text']
以下為我的關注用戶的微博:
拿上邊代碼為例,這里我們獲取的信息有: