特别在于当前的代码没有考虑到这些问题。针对您提供的网站和需求,我已经改动代码并给出了合理有效的代码,请参考如下:

import requests
import os
from bs4 import BeautifulSoup

# 创建保存图片的文件夹
if not os.path.exists('images'):
    os.makedirs('images')

# 网站链接
url = 'https://www.biqug.org/index.php/comic/huyaoxiaohongniang'

# 发起请求
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 获取前10;个章节的链接
chapter_links = []
chapter_elements = soup.select('.mulu > ul > li > a')
for element in chapter_elements[:10]:
    chapter_links.append(element['href'])

# 循环每个章节链接
for link in chapter_links:
    chapter_url = 'https://www.biqug.org' + link

    # 发起请求
    response = requests.get(chapter_url)
    soup = BeautifulSoup(response.text, 'html.parser')

    # 获取章节标题
    chapter_title = soup.select_one('.nr_title').text.strip()

    # 创建保存该章节图片的文件夹
if not os.path.exists(f'images/{chapter_title}'):
        os.makedirs(f'images/{chapter_title}')

    # 获取该章节中的图片链接
image_links = []
image_elements = soup.select('.nr_imgs > img')
for element in image_elements:
    image_links.append(element['src'])

    # 循环每个图片链接并保存图片
for i, link in enumerate(image_links):
    image_url = 'https://www.biqug.org' + link

    # 发起请求
    response = requests.get(image_url)

    # 保存图片到本地
with open(f'images/{chapter_title}/{i+1}.jpg', 'wb') as f:
    f.write(response.content)
    print(f'Saved image {i+1} in {chapter_title}')

请确保在运行代码之前安装必需的依赖包,如果requestsbeautifulsoup4。加上,该代码可以保存每个章节中的图片到以章节标题命名的文件夹中。

希望这次能满足您的需求,如果有任何问题,请允许我看看。

Python 爬取漫画网站图片:克服反爬虫机制和异步加载

原文地址: https://www.cveoy.top/t/topic/pw67 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录