请考虑到网站的反爬虫机制考虑到漫画章节的链接是短链接考虑到漫画页面是使用Javascript异步请求动态加载的。网站是httpswwwbiqugorgindexphpcomichuyaoxiaohongniang我需要爬取其中前10个章节每个章节中漫画的图片内容并保存到本地。请给出合理有效的代码。
以下是一个使用Python的代码示例,爬取给定网站前10个章节中每个章节的漫画图片,并保存到本地:
import requests
import os
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
}
# 目标网站链接
url = 'https://www.biqug.org/index.php/comic/huyaoxiaohongniang'
# 发送请求获取网页内容
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取前10个章节的链接
chapter_links = []
for link in soup.find_all('a', class_='chapter-list'):
chapter_links.append(link['href'])
# 爬取每个章节的漫画图片
for i in range(10):
chapter_url = chapter_links[i]
chapter_response = requests.get(chapter_url, headers=headers)
chapter_soup = BeautifulSoup(chapter_response.text, 'html.parser')
# 获取每个漫画图片的链接
image_links = []
for img in chapter_soup.find_all('img', class_='comicimg'):
image_links.append(img['src'])
# 创建文件夹保存图片
folder_path = f'Chapter {i+1}'
os.makedirs(folder_path, exist_ok=True)
# 下载图片并保存到本地
for j, image_link in enumerate(image_links):
image_response = requests.get(image_link, headers=headers)
image_path = f'{folder_path}/image{j+1}.jpg'
with open(image_path, 'wb') as image_file:
image_file.write(image_response.content)
print(f'Saved {image_path}')
print('爬取完成!')
请注意,这只是一个基本示例,具体的反爬虫机制可能会有所不同,你可能需要进一步分析网站反爬虫机制,并进行相应的处理,例如添加延时、使用代理、模拟登录等
原文地址: https://www.cveoy.top/t/topic/hN2Z 著作权归作者所有。请勿转载和采集!