爬取博客的图片并且将它存储到响应的目录

news/2024/7/19 12:09:20 标签: python, 笔记, 爬虫, 网络爬虫

目录

前言

思想

注意

不多说解释了,贴代码吧

config.json

Get_blog_img.py

把之前的写的代码也贴上

Get_blog_id.py

主函数

main.py

运行结果


前言

在上一篇博客中我们介绍了如何爬取博客链接

利用python爬取本站的所有博客链接-CSDN博客文章浏览阅读740次,点赞5次,收藏16次。定义一个json配置文件方便管理现在文件只有用户名称,后续可加配置读取用户名称,并且将其拼接成csdn个人博客链接type=blog"https://blog.csdn.net/mumuemhaha/article/details/136375650在这一篇博客中我们介绍如何爬取博客中文章的图片

github同步更新

GitHub - mumuhaha487/Get_csdnContribute to mumuhaha487/Get_csdn development by creating an account on GitHub.icon-default.png?t=N7T8https://github.com/mumuhaha487/Get_csdn

思想

首先同样利用request库进行爬取源代码然后利用正则表达式来筛选信息

需要注意的是分别把链接

https://img-blog.csdnimg.cn/xxx/xxx.png

和/xxx/xxx.png存储起来

前者用于爬取链接,后者用于区分存储在本地的路径

之前想利用re库来判断“/”符号进而提取文件目录,但是后面发现python有现成的库用来提取路径和文件名

利用

python">os.path.split

函数即可

注意

多余的不多说明了部分博客游客看不了,注意配置cookie(最好配置自己的cookie)

在config.json中即可

不多说解释了,贴代码吧

config.json

{
  "blog_id": "mumuemhaha",
  "cookie" : "your_cookie",
  "img_path": "img"
}

注意配置cookie,爬取下来的文件保存在img目录中

Get_blog_img.py

python">import requests
import json
import re
import os
def Get_blog_img(url_1):
    with open("./config.json", 'r') as file_1:
        data_1 = json.load(file_1)

    cookie_1=data_1["cookie"]
    img_1=data_1["img_path"]
    head_1={
        "User-Agent" :"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
        "Cookie" : cookie_1
    }
    req_1=requests.get(url=url_1,headers=head_1)
    re_1='src="(https://img-blog.csdnimg.cn.*?.png)"'
    re_2='src="https://img-blog.csdnimg.cn/(.*?.png)"'
    img_ids=re.findall(re_2,req_1.text)
    img_urls=re.findall(re_1,req_1.text)
    for i in range(len(img_ids)):
        dir_name,file_name=os.path.split(img_ids[i])
        if dir_name:
            os.makedirs(f"{img_1}/{dir_name}",exist_ok=True)
        img_response=requests.get(url=img_urls[i],headers=head_1)
        if dir_name:
            with open(f'{img_1}/{dir_name}/{file_name}', 'wb') as f:
                f.write(img_response.content)
        else:
            with open(f'{img_1}/{file_name}', 'wb') as f:
                f.write(img_response.content)

把之前的写的代码也贴上

Get_blog_id.py

python">from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains  # 用于自动化框架执行动作
import time  # 延时操作,方便网站加载完全
import json  # 用于读取配置信息
import re  # 从源代码中提取文章的链接
def Get_blog_id():
    with open("./config.json", 'r') as file_1:
        data_1 = json.load(file_1)

    blog_id = data_1["blog_id"]
    url_1 = f"https://blog.csdn.net/{blog_id}?type=blog"
    driver = webdriver.Chrome()
    driver.get(url_1)
    for i in range(10000):
        time.sleep(0.5)
        actions = ActionChains(driver)
        actions.send_keys(Keys.PAGE_DOWN)  # 可以多次发送 PAGE_DOWN 来实现滚动的距离
        actions.perform()
        if i % 10 == 0:  # 每滑动 10 次进行判断
            prev_page_source = driver.page_source  # 获取前一次滑动后的页面源码
            time.sleep(2)  # 等待页面加载
            current_page_source = driver.page_source  # 获取当前页面源码

            if prev_page_source == current_page_source:
                print("网站滑倒底了,跳出循环...")
                break

    req_1 = driver.page_source
    re_1 = '<a data-v-6fe2b6a7="" href="(.*?)"'
    blog_urls = re.findall(re_1, req_1)
    print(f"文章个数为{len(blog_urls)}(看看是不是全爬下来了)")
    return blog_urls

主函数

main.py

python">import Get_blog_img
import Get_blog_id
blog_urls=Get_blog_id.Get_blog_id()
for blog_url in blog_urls:
    Get_blog_img.Get_blog_img(blog_url)

运行结果

可以看到,爬取下来了 


http://www.niftyadmin.cn/n/5407815.html

相关文章

Vue.js 实用技巧:深入理解 Vue.mixin

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

高漫反射透光率积分球

透光率积分球是一个内部涂有白色漫反射材料的空腔球体&#xff0c;用于测量材料透光性能的光学设备。其基本原理是光通过采样口被积分球收集&#xff0c;在积分球内部经过多次反射后非常均匀地散射在积分球内部。积分球的主要功能是作为光收集器&#xff0c;被收集的光可以用作…

STM32CubeIDE基础学习-新建STM32CubeIDE基础工程

STM32CubeIDE基础学习-新建STM32CubeIDE基础工程 前言 有开发过程序的朋友都清楚&#xff0c;后面开发是不需要再新建工程的&#xff0c;一般都是在初学时或者有特殊需要的时候才需要新建项目工程的。 后面开发都是可以在这种已有的工程上添加相关功能就行&#xff0c;只要前…

[C语言]——操作符

目录 一.算术操作符&#xff1a;、-、*、/、% 1. 和 - 2.* 3./ 4.% 二.赋值操作符&#xff1a;和复合赋值 1.连续赋值 2.复合赋值符 三.单目操作符&#xff1a;、--、、- 1.和-- 1.1前置 1.2后置 1.3前置-- 2. 和 - 四.强制类型转换 一.算术操作符&#xff1a;…

中文文本分类_1(pytorch 实现)

import torch import torch.nn as nn import torchvision from torchvision import transforms, datasets import os, PIL, pathlib, warningswarnings.filterwarnings("ignore") # 忽略警告信息# win10系统 device torch.device("cuda" if torch.cuda.i…

【自然语言处理六-最重要的模型-transformer-上】

自然语言处理六-最重要的模型-transformer-上 什么是transformer模型transformer 模型在自然语言处理领域的应用transformer 架构encoderinput处理部分&#xff08;词嵌入和postional encoding&#xff09;attention部分addNorm Feedforward & add && NormFeedforw…

(MATLAB)第三章-MATLAB基础知识

目录 3.1 MATLAB命令的组成 3.1.1 基本符合 3.1.2 功能符号 3.1.3 常用指令 3.2 数据类型 3.2.1 变量于长亮 3.2.2数值 3.3 运算符 3.3.1算术运算符 3.3.2 关系运算符 返回值0和1分别表示不满足和满足关系 3.3.3 逻辑运算符&#xff08;真1假0&#xff09; 3.4 函数运算 3.…

【对比】Gemini:听说GPT-4你小子挺厉害

前言 &#x1f34a;缘由 谷歌连放大招:Gemini Pro支持中文,Bard学会画画 &#x1f3c0;事情起因&#xff1a; 一心只读圣贤书的狗哥&#xff0c;不经意间被新闻吸引。【谷歌最新人工智能模型Gemini Pro已在欧洲上市 将与ChatGPT竞争】&#xff0c; 平时玩弄ChatGPT-4很熟练了…