爬取一条微博的所有转发链接

来源:互联网 发布:艺术二维码生成器软件 编辑:程序博客网 时间:2024/06/08 18:08

需求分析

因朋友需求,需要删除在微博上的一些非法转发,故给出链接的根节点,只查询根节点的第一层节点,并删除第一层节点的所有转发。

本人python初学者,有什么写的不好的地方,请指出,与大家一起学习交流。
文章结尾附上完整代码,同时还有详细的说明文档,请自行下载。

  • 前期准备
    安装python3x
    导入requests、bs4等必须的库

导入命令

pip install requestspip install bs4
  • 网页分析
    需要在简易版微博上爬取
    验证微博登录的cookie
    爬取所有转发的人的id(每个人的id是固定的)和文章号(同一篇文章每个人会生成不同的文章号)

代码分析

  1. 登录cookie存储
    打开网址:https://weibo.cn/pub
    点击登录
    打开调试工具,即按F12,同时调到Network
    输入帐号密码点击登录
    在调试工具中找到weibo.cn,复制cookie

  2. 获取单个页面的所有转发链接

def getComment(url,file):    """     获取单个链接页面中的转发连接    :param url:评论页面链接    :param file: 文件对象    """    try:        html = requests.get(url, cookies=cook).content        soup = BeautifulSoup(html, "html.parser")        r = soup.findAll('div', attrs={"class": "c"})        for e in r:            size = 0            name = ''            uid = ''            article = ''            for item in e.find_all('a',href=re.compile("/u")):                size = size + 1                name = item.text                uid = item.get('href').split("/")[2];            for item in e.find_all('span',attrs={"class":"cc"}):                size = size + 1                str = item.find('a').get("href").split("/")                article = str[2]            if size == 2:                link = 'https://weibo.com' + '/' + uid + '/' + article                try:                    file.write(link + '\n')                except IOError:                    print("存入目标文件有误,请重新选择文件")                    raise IOError("存入目标文件有误,请重新选择文件")    except Exception as e:        print("**********请求连接失败**********")        raise Exception()
  1. 得到一个根节点的所有转发页面链接,即获取共多少页转发(一篇微博可能有几十页的转发量)
def getUrlList(url):    """    获取一个根的所有的转发页面链接    :param url: 主页面链接    :return: 所有评论链接    """    form_action = url    url = comment_page + url    html = requests.get(url, cookies=cook).content    soup = BeautifulSoup(html, "html.parser")    list = []    form = soup.find("form", attrs={"action": "/repost/" + form_action})    a = form.find('a').get('href')    b = a[0:len(a)-1] #页面的第一部分    c = form.find("div").text.split("/")[1]    d = len(c) -1    e = c[0:d]    for i in range(1,int(e) + 1):        list.append(page + b + str(i))    return list
  1. main函数

在任意地方创建input.txt,每一行是一个根文章的文章号

input.txtFnp688CaAFnp688CaAFnp688CaA

创建或不创建output.txt都可以指定输出文件名和路径即可

if __name__ == '__main__':    use_reading()    input_file_name = r"C:\Users\syl\Desktop\input.txt"    output_file_name = r"C:\Users\syl\Desktop\output.txt"    getTreeComment(input_file_name,output_file_name)

使用文档说明,点这里下载

完整代码如下

# -*- coding: utf-8 -*-import codecsimport requestsfrom bs4 import BeautifulSoupimport reimport timeimport osimport traceback# ***********基本信息请谨慎更改**********page = 'https://weibo.cn' # 简易版微博首页地址main_page = 'https://weibo.com' # 正式版微博首页地址comment_page = 'https://weibo.cn/repost/' #简易版微博评论页面地址##请登录帐号查找自己的cookie填入此处cook = {"Cookie":"请自行更换"} #放入你的cookie信息。# ***************************************def getUrlList(url):    """    获取一个根的所有的转发页面链接    :param url: 主页面链接    :return: 所有评论链接    """    form_action = url    url = comment_page + url    html = requests.get(url, cookies=cook).content    soup = BeautifulSoup(html, "html.parser")    list = []    form = soup.find("form", attrs={"action": "/repost/" + form_action})    a = form.find('a').get('href')    b = a[0:len(a)-1] #页面的第一部分    c = form.find("div").text.split("/")[1]    d = len(c) -1    e = c[0:d]    for i in range(1,int(e) + 1):        list.append(page + b + str(i))    return listdef getComment(url,file):    """     获取单个链接页面中的转发连接    :param url:评论页面链接    :param file: 文件对象    """    try:        html = requests.get(url, cookies=cook).content        soup = BeautifulSoup(html, "html.parser")        r = soup.findAll('div', attrs={"class": "c"})        for e in r:            size = 0            name = ''            uid = ''            article = ''            for item in e.find_all('a',href=re.compile("/u")):                size = size + 1                name = item.text                uid = item.get('href').split("/")[2];            for item in e.find_all('span',attrs={"class":"cc"}):                size = size + 1                str = item.find('a').get("href").split("/")                article = str[2]            if size == 2:                link = 'https://weibo.com' + '/' + uid + '/' + article                try:                    file.write(link + '\n')                except IOError:                    print("存入目标文件有误,请重新选择文件")                    raise IOError("存入目标文件有误,请重新选择文件")    except Exception as e:        print("**********请求连接失败**********")        raise Exception()def getAllComment(list,filename):    """    获取一个根节点的所有评论链接    :param list: 评论页面集合    """    file = codecs.open(filename, "w", "utf-8")    for link in list:        try:            getComment(link, file)        except Exception as e:            print("**********请重新运行程序**********")            break        time.sleep(1)    file.close()def readFile(filename):    """    获取根节点    :param filename:根节点所在的文件    :return: 根节点集合    """    list = []    if not os.path.isfile(filename):        print("*******************文件不存在请检查文件是否存在*******************")        raise Exception("*******************文件不存在请检查文件是否存在*******************")        return    file = open(filename)    lines = file.readlines()  # 调用文件的 readline()方法    for line in lines:        if len(line) != 0:            a = line.strip()            list.append(a)    return listdef getTreeComment(input_file_name,output_file_name):    """    获取文件中所有连接的转发链接    :param input_file_name:读取文件    :param output_file_name:输入文件    """    start = time.time()    print("-----------计时开始-----------")    output_file_name = path_change(output_file_name)    i = 0    tree_list = readFile(input_file_name)    for link in tree_list:        i = i + 1        print("**********************写入第" + str(i) + "个文件,请耐心等待***************************")        getAllComment(getUrlList(link),output_file_name + str(i) + '.txt')        print("**********************第" + str(i) + "个文件,写入完毕*********************************")    total_time = time.time() - start    print(u"-----------总共耗时:%f 秒-----------" % total_time)def path_change(filename):    str = filename[0:len(filename)-4]    return strdef use_reading():    print("******************************************************************************")    print("*                                使用必读                                    *")    print("*                                一般来说每写入100个链接大约耗时18s            *")    print("*                                如果转发链接大于1w条,请耐心等待            *")    print("*                                使用前请耐心阅读使用文档                    *")    print("*****************************************************************************")if __name__ == '__main__':    use_reading()    input_file_name = r"C:\Users\syl\Desktop\main.txt"    output_file_name = r"C:\Users\syl\Desktop\douban.txt"    getTreeComment(input_file_name,output_file_name)
原创粉丝点击