帮我写一个爬取图片的爬虫
时间: 2023-06-10 21:07:23 浏览: 116
好的,以下是一个简单的Python爬虫代码,用于爬取指定网站上的图片:
```python
import requests
from bs4 import BeautifulSoup
import os
url = "https://www.example.com" # 需要爬取图片的网站首页
save_folder = "images" # 图片存储的文件夹名称
# 创建图片存储文件夹
if not os.path.exists(save_folder):
os.makedirs(save_folder)
# 发送请求并解析HTML
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
# 获取所有图片链接,并依次下载
for img in soup.find_all("img"):
img_url = img.get("src")
if not img_url.startswith("http"):
img_url = url + img_url
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(f"已下载图片:{img_url}")
```
请注意,这个爬虫只会爬取首页上的图片,并且不会对重复的图片进行去重。如果需要爬取更多页面上的图片,需要对代码进行改进。同时,爬取图片也需要遵守相关法律法规,不要滥用爬虫技术。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)