pycharm中用python的request库和BeautifulSoup库爬取彼岸图网中的图片并下载的代码及注释
时间: 2024-06-09 09:06:53 浏览: 9
以下是使用Python的requests库和BeautifulSoup库爬取彼岸图网中的图片并下载的示例代码及注释:
```python
import os
import requests
from bs4 import BeautifulSoup
# 设置要爬取的网页链接和保存图片的文件夹
url = 'https://www.netbian.com/weimei/'
save_folder = 'images'
# 创建保存图片的文件夹
if not os.path.exists(save_folder):
os.makedirs(save_folder)
# 发送GET请求并获取响应内容
response = requests.get(url)
html = response.text
# 解析HTML内容
soup = BeautifulSoup(html, 'html.parser')
# 查找所有图片标签并依次下载图片
for img in soup.find_all('img'):
# 获取图片链接
img_url = img['src']
# 如果链接不是以http开头,说明是相对路径,需要加上网页链接
if not img_url.startswith('http'):
img_url = url + img_url
# 发送GET请求并保存图片
response = requests.get(img_url)
with open(os.path.join(save_folder, os.path.basename(img_url)), 'wb') as f:
f.write(response.content)
# 输出下载图片的文件名
print('Downloaded:', os.path.basename(img_url))
```
注释:
- 第1行:导入所需的模块。
- 第4行:设置要爬取的网页链接。
- 第5行:设置保存图片的文件夹。
- 第8-11行:创建保存图片的文件夹。
- 第14行:发送GET请求并获取响应内容。
- 第16行:解析HTML内容。
- 第19-27行:查找所有图片标签并依次下载图片。
- 第21行:获取图片链接。
- 第24-27行:发送GET请求并保存图片。
- 第30行:输出下载图片的文件名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)