使用Python代码请针对网址:https://bbs.zol.com.cn/dcbbs/d15.html 编写爬虫。 要求将 ZOL论坛 > 摄影论坛 > 摄影作品论坛 > 动物植物论坛 该论坛模块下所有帖子的图片爬取回来,每个帖子一个文件夹(文件夹名使用帖子名命名),文件夹中存放该帖子中所有图片。
时间: 2024-04-07 20:31:50 浏览: 13
好的,我可以为您提供一份简单的 Python 爬虫代码来实现您的需求。首先,需要安装 requests、BeautifulSoup 和 os 这三个 Python 库。您可以使用以下命令来安装它们:
```
pip install requests
pip install beautifulsoup4
```
然后,您可以使用以下代码来实现您的需求:
```python
import requests
from bs4 import BeautifulSoup
import os
# 设置请求头,模拟浏览器请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 目标页面的URL
url = 'https://bbs.zol.com.cn/dcbbs/d15.html'
# 发送请求,获取页面源码
response = requests.get(url, headers=headers)
html = response.text
# 解析页面源码,获取所有帖子的URL
soup = BeautifulSoup(html, 'html.parser')
links = soup.select('#showtopic .topic > a')
# 循环遍历每个帖子的URL
for link in links:
# 发送请求,获取帖子页面源码
post_url = link['href']
response = requests.get(post_url, headers=headers)
html = response.text
# 解析帖子页面源码,获取帖子标题和所有图片的URL
soup = BeautifulSoup(html, 'html.parser')
title = soup.select_one('.post_title > h1').text
img_links = soup.select('.post_content img')
# 创建文件夹,用于存放当前帖子的所有图片
folder_name = title.replace('/', '').replace('\\', '').replace(':', '').replace('*', '').replace('?', '').replace('"', '').replace('<', '').replace('>', '').replace('|', '')
if not os.path.exists(folder_name):
os.makedirs(folder_name)
# 循环遍历当前帖子的所有图片的URL,下载图片并保存到文件夹中
for index, img_link in enumerate(img_links):
img_url = img_link['src']
img_name = os.path.join(folder_name, f'{index+1}.jpg')
img_data = requests.get(img_url, headers=headers).content
with open(img_name, 'wb') as f:
f.write(img_data)
```
这段代码会依次爬取 ZOL论坛 > 摄影论坛 > 摄影作品论坛 > 动物植物论坛 下的所有帖子,将每个帖子的所有图片下载并保存到以帖子名命名的文件夹中。注意,因为帖子名中可能包含不能作为文件夹名的字符,所以在创建文件夹时需要进行一些处理。