1. 程式人生 > >使用新浪微博官方API抓取微博資料(Python版)

使用新浪微博官方API抓取微博資料(Python版)

一、安裝環境

二、一個簡單的例子

# coding=utf-8
from weibo import APIClient
import webbrowser  # python內建的包

APP_KEY = '你的app_key'  # 你的app_key
APP_SECRET = '你的app_secret'  # 你的app_secret
CALLBACK_URL = 'http://www.baidu.com'  # 網站回撥地址

# 在網站設定"使用微博賬號登陸"的連結,當用戶點選連結後,引導使用者跳轉至如下地址
# 利用官方微博ADK
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

# 使用者授權後,將跳轉至網站回撥地址,並附加引數code=abcd1234

# 獲取URL引數code:
print "輸入url中code後面的內容後按回車鍵:"
code = raw_input()   # 人工輸入網址後面的code內容


r = client.request_access_token(code)  # 獲得使用者授權

# 儲存access_token, expires_in
access_token = r.access_token  # 新浪返回的token,類似abc123xyz456
expires_in = r.expires_in
# 設定得到的access_token,client可以直接呼叫API了
client.set_access_token(access_token, expires_in)

# 可以列印下看看裡面都是什麼東西
# print client.statuses__public_timeline()
statuses = client.statuses__public_timeline()['statuses']
length = len(statuses)
# 輸出了部分資訊
for i in range(0, length):
    print u"微博建立時間:" + statuses[i]['created_at']
    print u'暱稱:' + statuses[i]['user']['screen_name']
    print u'簡介:' + statuses[i]['user']['description']
    print u'位置:' + statuses[i]['user']['location']
    print u'微博:' + statuses[i]['text']