要自動發微博最簡單的辦法無非是調用新浪微博的API(因為只是簡單的發微博,就沒必要用它的SDK了)。參考開發文檔http://open.weibo.com/wiki/API進行代碼編寫
創建應用
要使用微博的API,需先要有個應用。隨便是個應用就行,可以到這里注冊一個站內應用應用注冊。注冊應用的主要目的是要獲得MY_APPKEY 和MY_ACCESS_TOKEN,如圖所示
獲取access_token
首先,調用https://api.weibo.com/oauth2/authorize接口,獲得code。
該接口有三個必須的參數:
- client_id:申請應用時分配的AppKey。
- redirect_url:就是創建應用中設置的回調地址
- response_type:響應類型,可設置為code
具體做法,就是在瀏覽器打開https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code。該方法會轉到授權頁面,授權之后會轉到http://www.example.com/response&code=CODE,記錄下該url中的CODE。
接着,調用https://api.weibo.com/oauth2/access_token接口,獲得access_token。
該接口有如下必須的參數:
- client_id:申請應用時分配的AppKey。
- client_secret:申請應用時分配的AppSecret。
- grant_type:請求的類型,填寫authorization_code
- code:調用authorize獲得的code值。
- redirect_uri: 就是創建應用中設置的回調地址
具體做法就是構建一個POST請求,再在返回的數據中找到access_token,保存下來。具體的Python代碼:
import requests
url_get_token = "https://api.weibo.com/oauth2/access_token"
#構建POST參數
playload = {
"client_id":"填入你的",
"client_secret":"填入你的",
"grant_type":"authorization_code",
"code":"上面獲得的CODE",
"redirect_uri":"你的回調用地址"
}
#POST請求
r = requests.post(url_get_token,data=playload)
#輸出響應信息
print r.text
如果正常的話,會返回下面這樣的json數據:
{"access_token":"我們要記下的","remind_in":"157679999","expires_in":157679999,"uid":"1739207845"}
根據返回的數據,access_token的值就是我們要的。其中remind_in的值是access_token的有效期,單位為秒,我們可以看到,這個時間有3、4年之久,足夠我們用了。
發表純文字微博
調用接口https://api.weibo.com/2/statuses/update.json發表文字微博,其參數如下
其中必須的:
- access_token: 就是我們上一步獲得的access_token
- status:要發布的微博文本內容,必須做URLencode,內容不超過140個漢字
具體代碼:
#發表文字微博的接口
url_post_a_text = "https://api.weibo.com/2/statuses/update.json"
#構建POST參數
playload = {
"access_token":"填入你的",
"status":"This is a text test@TaceyWong"
}
#POST請求,發表文字微博
r = requests.post(url_post_a_text,data = playload)
如果正常,會有向下面這樣的結果
發表帶圖片的微博
調用接口http://open.weibo.com/wiki/2/statuses/upload發表圖片微博,其參數如下:
其中必須的參數:
- access_token: 就是我們上一步獲得的access_token
- status:要發布的微博文本內容,必須做URLencode,內容不超過140個漢字
- pic:要發表的圖片,采用multipart/form-data編碼方式
具體的代碼:
#發表圖文微博的接口
url_post_pic = "https://upload.api.weibo.com/2/statuses/upload.json"
#構建文本類POST參數
playload={
"access_token":"",
"status":"Test:Post a text with a pic & AT someone@丸子覠"
}
#構建二進制multipart/form-data編碼的參數
files={
"pic":open("logo.png","rb")
}
#POST請求,發表微博
r = requests.post(url_post_pic,data=playload,files = files)
如果正常,結果會像下面這樣:
注:requests的具體用法請參考[requests文檔](http://docs.python-requests.org/en/master/)