【python】用python自動發微博

首先聲明一下,這只是一個小demo,用來作為我學習python的練習,一個除了學(zhuang)習(bi)并無大用的小腳本而已。

咳咳,下面開始手把手教學,大家好好聽啊【敲黑板】

第一步:你應該要有自己的app keyapp scret

移動API申請

點擊上面這個鏈接就可以進入開發者中心申請app keyapp scret啦,當然前提是你要完善一下個人信息,只要基本信息完善一下即可。然后激活郵箱,你申請一個就可以得到上面的所需信息啦。

之后,在高級設置中將回調函數修改一下:https://api.weibo.com/oauth2/default.html ,這個需要和之后的python code里面的 callback url一致!!!

第二步:安裝所需插件

這里要感謝一下廖雪峰大牛提供的SDK:sinaweibopy

pip install sinaweibopy
pip install PIL

確認一下你的python版本,這里用的是python 2.7,會用2.7,3自然不是什么難事。

python Code

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'zjbao123'


from weibo import APIClient
import weather

def get_access_token(app_key, app_secret, callback_url):
    client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=callback_url)
    # 獲取授權頁面網址
    auth_url = client.get_authorize_url()
    print auth_url

    # 在瀏覽器中訪問這個URL,會跳轉到回調地址,回調地址后面跟著code,輸入code
    code = raw_input("Input code:")
    r = client.request_access_token(code)
    access_token = r.access_token
    # token過期的UNIX時間
    expires_in = r.expires_in
    print 'access_token:', access_token
    print 'expires_in:', expires_in

    return access_token, expires_in
def init_login():
    app_key = 'xxxxxxx'
    app_secret = 'xxxxxxxxxx'
    callback_url = 'https://api.weibo.com/oauth2/default.html'

    access_token, expires_in = get_access_token(app_key, app_secret, callback_url)
    # 上面的語句運行一次后,可保存得到的access token,不必每次都申請
    #print "access_token = %s, expires_in = %s" % (access_token, expires_in)
    # access_token = 'xxxxxxxx'
    # expires_in = 'xxxxxx'

    client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=callback_url)
    client.set_access_token(access_token, expires_in)
    return client


def send_pic(client,picpath,message):
    # send a weibo with img
    f = open(picpath, 'rb')
    mes = message.decode('utf-8')
    client.statuses.upload.post(status=mes, pic=f)
    f.close()  # APIClient不會自動關閉文件,需要手動關閉
    print u"發送成功!"

def send_mes(client,message):
    utext = unicode(message,"UTF-8")
    client.post.statuses__update(status=utext)
    print u"發送成功!"


if __name__ == '__main__':
    client = init_login()
    weather.draw_pic(weather.weather())
    mes = "鮑先森又被盜號啦哈哈哈,我特意來跟大家匯報杭州今日天氣:"
    send_pic(client,'2.jpg',mes)

看完源碼會發現,這個weather是什么東西?我看這個發微博單調無比,給他新增了一個功能,根據每日天氣預報,繪制一張天氣預報的圖。

天氣預報

weather.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'zjbao123'
import json
import urllib2
from PIL import Image,ImageDraw,ImageFont

def weather():
    # 獲取每日天氣數據
    try:
        url = 'http://api.map.baidu.com/telematics/v3/weather?location=%E6%9D%AD%E5%B7%9E&output=json&ak=KPGX6sBfBZvz8NlDN5mXDNBF&callback='
        s=json.loads(urllib2.urlopen(url).read())
        s1 = s["results"][0]["weather_data"][0]["temperature"]
        s2 = s["results"][0]["weather_data"][0]["weather"]
        # print s["results"][0]["currentCity"]
        # print s["results"][0]["weather_data"][0]["temperature"]
        # print s["results"][0]["weather_data"][0]["weather"]
        return s1,s2
    except :
        print"error"
def draw_pic(l):
    img = Image.open('test.jpg')
    draw = ImageDraw.Draw(img)
    myfont = ImageFont.truetype(u'C:/windows/fonts/逼格銳線體簡4.0 (2).TTF', size=50) #字體自己改
    draw.text((img.size[0]/6,img.size[1]/5),unicode(l[0]),font=myfont, fill = (0,177,106))
    draw.text((img.size[0]/3,img.size[1]/5+150),unicode(l[1]),font=myfont, fill = (0,128,131))
    img.save('2.jpg','jpeg')
    print 'ok'

結果如圖示:


微博截圖

最后貼上我的github鏈接吧:repo


參考:
http://www.guokr.com/post/475564/

https://www.zhihu.com/question/36960036

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容