python 呼叫微博API批量回復微博評論
阿新 • • 發佈:2019-02-20
標頭檔案
import urllib
import urllib.requestimport http.cookiejar
import urllib.parse
import sys
import re
import base64
import json
import math
print('自動評論')
access_token = '2.00787Z_EVNDC**************'
這一段迷上了python,又經常使用新浪微博,就想搞這麼個東西,鬧著玩的
建立APP,什麼的就不說了,回撥地址用下面的:
'redirect_uri'設為'https://api.weibo.com/oauth2/default.html'
access_token我是手動新增url開啟獲取code,通過code獲取的。
某條微博的id,即下面的mymid,需要轉化成id,API有介紹。
'''mid->id'''mymid = 'BrSr7g51Q'
def get_id(mid):
url_mid = 'https://api.weibo.com/2/statuses/queryid.json'
values = {'access_token':'2.00787Z_EVNDCKDafde730d76XfRlOC',
'mid':mid,
'isBase62':'1',
'type':'1'}
data = urllib.parse.urlencode(values)
data = data.encode('UTF-8')
url_t = 'https://api.weibo.com/2/statuses/queryid.json?access_token=2.00787Z_EVNDCKDafde730d76XfRlOC&mid=BrSr7g51Q&type=1&isBase62=1'
url = 'https://api.weibo.com/2/statuses/queryid.json?access_token=2.00787Z_EVNDCKDafde730d76XfRlOC&type=1&isBase62=1&mid=' + mid
html = urllib.request.urlopen(url)
id = json.loads(html.read().decode('UTF-8'))
print (id['id'])
return id['id']
回覆的小函式,需要幾個引數,請查閱API。
def reply(cid,id,user):
values ={'access_token':'2.00787Z_EVNDCKDafde730d76XfRlOC',
'cid':cid,
'id':id,
'comment':'你好!python %s 評論!:)' % user}
url_reply = 'https://api.weibo.com/2/comments/reply.json'
data = urllib.parse.urlencode(values)
data =data.encode('UTF-8')
url =urllib.request.Request(url_reply,data)
html = urllib.request.urlopen(url)
獲取所有評論資訊,利用評論獲取評論者資訊,資訊包含reply需要的cid,id等資訊。
'''通過id獲取某條微博的所有評論資訊'''
def show(id):
url_show = 'https://api.weibo.com/2/comments/show.json'
values = {'access_token':'2.00787Z_EVNDCKDafde730d76XfRlOC',
'id':id}
data = urllib.parse.urlencode(values)
data = data.encode('UTF-8')
url = 'https://api.weibo.com/2/comments/show.json?access_token=2.00787Z_EVNDCKDafde730d76XfRlOC&id=' + id
html = urllib.request.urlopen(url)
s = json.loads(html.read().decode('UTF-8'))
j = s['total_number']
for i in range(0,j):
print(i)
cid = s['comments'][i]['mid']
print(cid)
user = s['comments'][i]['user']['screen_name']
reply(cid,id,user)
show(get_id(mymid))
大功告成,花了好幾天,從不懂到這麼個東西,浪費了很多重要時間。解釋就不這麼詳細了。轉載請註明來源!!!!