python 调用微博API批量回复微博评论

来源:互联网 发布:淘宝无法上架宝贝 编辑:程序博客网 时间:2024/06/02 03:35

头文件

import urllib

import urllib.request
import 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))


大功告成,花了好几天,从不懂到这么个东西,浪费了很多重要时间。解释就不这么详细了。转载请注明来源!!!!




















0 0