用 python 获取新浪微博最近发布内容的时候调用 public_timeline() 函数的返回值是个 jsonDict 对象, 首先需要将该对象通过 JSON.dumps 函数转换成字符串, 然后对该字符串用 GBK 进行编码和解码, 注意编码的时候函数 encode 的第二个参数要使用 ignore(默认是 strict), 以防止当解码错误的时候报错而使程序意外退出 .
- import webbrowser
- import sinaweibopy3
- from time import sleep
- import JSON
- def getLotsOfWeibo(searchStr):
- APP_KEY='你的 key'
- APP_SECRET='你的密码'
- REDIRECT_URL='https://api.weibo.com/oauth2/default.html'
- client=sinaweibopy3.APIClient(app_key=APP_KEY,app_secret=APP_SECRET,redirect_uri=REDIRECT_URL)
- url = client.get_authorize_url()
- print(url)
- webbrowser.open_new(url)
- result = client.request_access_token(
- input("please input code :")) # Enter the CODE obtained in the authorized address
- print(result)
- client.set_access_token(result.access_token, result.expires_in)
- t=client.public_timeline()
- t1=JSON.dumps(t,ensure_ascii=False)
- t1=t1.encode('gbk','ignore').decode('gbk')# 采用 GBK 打印, 忽略编码错误否则会报错
- print (t1) # get the latest public Weibo
来源: http://www.bubuko.com/infodetail-2934063.html