Python爬虫-爬取B站番剧封面

本文是本人最近学习Python爬虫所做的小练习。如有侵权,请联系删除

页面获取url

代码

python 复制代码
import requests
import os
import re

# 创建文件夹
path = os.getcwd() + '/images'
if not os.path.exists(path):
    os.mkdir(path)

# 当前页数
page = 1
# 总页数
total_page = 2

# 自动翻页,获取全部数据
def get_data():
    global page, total_page
    while page <= total_page:
        # 地址
        url = f"https://api.bilibili.com/pgc/season/index/result?st=1&order=3&season_version=-1&spoken_language_type=-1&area=-1&is_finish=-1&copyright=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&sort=0&page={page}&season_type=1&pagesize=20&type=1"
        # 请求头
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 SLBrowser/9.0.3.1311 SLBChan/105',
        }
        # 发送请求
        response = requests.get(url, headers=headers)
        # json数据格式
        items = response.json()
        # 循环遍历
        for data in items['data']['list']:
            # 标题
            title = data.get('title')
            # 封面
            cover = data.get('cover')
            # 下载图片到images文件夹中,文件名:title
            if title != '' and cover != '':
                download_image(title, cover)

        total = items.get('data')['total']
        size = items.get('data')['size']
        total_page = get_page_count(total, size)
        page += 1

# 下载图片
def download_image(title, cover):
    # 请求头
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 SLBrowser/9.0.3.1311 SLBChan/105',
    }
    res = requests.get(cover, headers=headers)

    # 判断标题是否含有\/:*?"<>|,文件命名不能含有这些,如果有,则用下划线_取代
    new_title = validateTitle(title)
    with open(path + '/' + new_title + '.jpg', mode='wb') as f:
        # 图片内容写入文件
        f.write(res.content)
        print(f"正在下载图片,图片名:{title}.jpg")

# 去除文件中的非法字符(正则表达式)
def validateTitle(title):
    pattern = r"[\\\/\:\*\?\"\<\>\|]"
    new_title = re.sub(pattern, '_', title)
    return new_title

# 求页数
def get_page_count(total, page):
    page_count = total // page
    if total % page != 0:
        page_count += 1
    return page_count

if __name__ == '__main__':
    get_data()

效果

相关推荐
IVEN_8 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang9 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮10 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling10 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮13 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽13 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers