当前位置:   article > 正文

动态爬虫(ajax)-爬取bilibili热门视频信息_爬取blbl热门视频

爬取blbl热门视频


前言

使用python爬虫爬取bilibli每日热门视频的数据
使用的第三方包有requests、my_fake_useragent

一、页面分析

在进行爬虫之前,我们先要对要爬取的页面进行分析,找到想要使用的接口
bilibili热门排行的地址:https://www.bilibili.com/v/popular/all?spm_id_from=333.851.b_7072696d61727950616765546162.3

在这里插入图片描述
如果我们直接进行http请求

import requests

url = 'https://www.bilibili.com/v/popular/all?' \
      'spm_id_from=333.851.b_7072696d61727950616765546162.3'
response = requests.get(url)
print(response.text)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

你会发现,返回回来的html里面什么信息都没有,更别提去处理了
在这里插入图片描述

这是因为,这个页面是使用动态html来进行生成的。你去请求这个url,只会返回一个框架,里面的内容是由ajax&js动态生成的
所以,我们要捕获对方用来动态生成页面的接口,以此来请求信息
————————————————————————————————————————

那么,怎么捕获这个接口呢?
在这个页面中,我们点击F12进入开发者模式,选取network栏,过滤XHR(即ajax)
在这里插入图片描述
我们发现,每加载一批新的视频,页面都会调用一个接口
在这里插入图片描述
瞅一眼response
在这里插入图片描述
可以看到,所有视频的信息都在里面
所以,可以确定使用接口名叫做https://api.bilibili.com/x/web-interface/popular
ps和pn都是参数,ps是page_size代表每一页的视频个数,pn是page_num,带表请求的页数
为了确定接口的可用性,用浏览器请求一次试试
在这里插入图片描述
灰常成功,可以开心地写程序了!

二、编写爬虫

这个爬虫的大概流程就是访问对于每一页发送一个请求,解析数据后保存到/popular/page_n文件夹下

1.引入库

import requests
import my_fake_useragent
import time
import json
import os
  • 1
  • 2
  • 3
  • 4
  • 5

2.发出请求

2.1生成请求头

def get_headers():
    """
    生成响应头
    :return: 生成的响应头
    """
    # 随机生成user_agent
    user_agent = my_fake_useragent.UserAgent()
    ua = str(user_agent.random())
    headers = {
        'user-agent': ua
    }
    return headers

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
'
运行

2.2发出请求并获取响应

def get_response(url, page=1, headers=get_headers()):
    """
    请求该url并获得响应
    :param url: 要请求的url
    :param page: 要请求的页数
    :param headers: 请求头部
    :return: 对于请求的响应
    """
    # 请求的参数
    params = {
        'ps': '20',
        'pn': str(page)
    }
    try:
        # 发出请求
        response = requests.get(url=url, params=params, headers=headers)
    except Exception as e:
        # 异常识别
        return None
    return response
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

3.解析响应的内容

刚刚返回的响应特别乱,根本看不懂里面的元素是怎么排列的,所以先去json在线解析解析一下
在这里插入图片描述
可以看到,list里面存储了所有的视频对象(Object),我们只需要把它取出来再遍历就行了

def parse_text(text=None):
    """
    解析响应的文本
    :param text:响应的文本
    :return: 由信息字典组成的列表[{info1}, {info2}, {info3}]
    """
    # 将json文件解析为字典
    data = json.loads(text)

    """
    data['data']是一个字典,包含若干数据
    data['data']['list']是一个字典组成的list,包含每个视频的信息
    """
    ret_list = []
    temp_dict = {}

    # 提取数据,生成返回列表
    for list_dict in data['data']['list']:
        # 保存标题
        temp_dict['title'] = list_dict['title']
        # 保存封面图片的地址
        temp_dict['pic'] = list_dict['pic']
        # 保存描述
        temp_dict['desc'] = list_dict['desc']

        # 保存投稿用户id
        temp_dict['name'] = list_dict['owner']['name']

        # 保存观看量
        temp_dict['view'] = list_dict['stat']['view']
        # 保存收藏数
        temp_dict['favorite'] = list_dict['stat']['favorite']
        # 保存投币数
        temp_dict['coin'] = list_dict['stat']['coin']
        # 保存分享数
        temp_dict['share'] = list_dict['stat']['share']
        # 保存点赞数
        temp_dict['like'] = list_dict['stat']['like']

        # 保存BV号
        temp_dict['bvid'] = list_dict['bvid']

        # 将字典添加到返回列表
        ret_list.append(temp_dict.copy())
        # 清空字典
        temp_dict.clear()

    return ret_list
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
'
运行

4.保存提取的信息到本地

def save_infos(infos=None, page=1, main_path=None):
    """
    保存信息到指定的文件夹
    :param main_path: 主路径
    :param infos: 要保存的信息
    :param page: 要保存到的文件夹序号
    """
    # 让编译器识别一下列表,好把里面的方法识别出来。。。手懒
    # infos = [].append(infos)

    # 创建子文件夹
    dir_path = main_path + '/page%d' % page
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)

    # 遍历读取到的信息
    for info in infos:
        # 以bv号命名文件
        file_path = dir_path + '/' +info['bvid'] + '.text'
        # 打开文件
        with open(file_path, 'w', encoding='utf-8') as fp:
            # 遍历字典
            for k, v in info.items():
                fp.write('%s: %s' % (str(k), str(v)))
                fp.write('\n')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
'
运行

5.康康主函数

def main():

    # 需要请求的url
    # 'https://api.bilibili.com/x/web-interface/popular?ps=20&pn=1'
    url = 'https://api.bilibili.com/x/web-interface/popular'

    # 创建主文件夹
    main_path = url.split('/')[-1]
    if not os.path.exists(main_path):
        os.mkdir(main_path)

    # 设定起始页码
    page_start = int(input('start: '))
    page_end = int(input('end: '))
    # page_start = 1
    # page_end = 1

    # 主循环开始
    # 主循环开始
    for i in range(page_end - page_start + 1):
        page_num = i + 1
        # 请求页面并获得响应
        print('第%d页开始下载……' % page_num)
        response = get_response(url=url, page=page_num, headers=get_headers())
        # 判断请求是否成功
        if not(response is None) and response.status_code == 200:
            # 请求成功
            # 获取并解析响应的内容
            text = response.text
            infos = parse_text(text)
            save_infos(infos=infos, page=page_num, main_path=main_path)
            print('第%d页下载完成' % page_num)
        else:
            # 请求失败
            print('!!第%d页请求失败!!' % page_num)
            continue

        # 文明爬虫!!!
        time.sleep(3)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
'
运行
if __name__ == '__main__':
    print('开始')
    start_time = time.time()
    main()
    end_time = time.time()
    print('完成<%f>' % (end_time - start_time))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

三、运行结果

在这里插入图片描述
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/900036
推荐阅读
相关标签
  

闽ICP备14008679号