使用 Python 爬虫程序自动下载网站中的图片
时间: 2024-06-09 21:09:47 浏览: 9
好的,这里给出一个简单的 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.mkdir(save_folder)
# 获取网页内容
response = requests.get(url)
html = response.text
# 解析网页内容,获取图片链接
soup = BeautifulSoup(html, "html.parser")
img_tags = soup.find_all("img")
# 下载图片并保存
for img in img_tags:
img_url = img.get("src")
if img_url.startswith("http"):
img_name = img_url.split("/")[-1]
img_path = os.path.join(save_folder, img_name)
img_data = requests.get(img_url).content
with open(img_path, "wb") as f:
f.write(img_data)
print(f"已保存图片 {img_path}")
```
上述程序使用了 requests 库和 BeautifulSoup 库。其中,requests 库用于获取网页内容,BeautifulSoup 库用于解析网页内容。程序首先获取指定网页的内容,然后解析出网页中的所有图片链接。最后,程序使用 requests 库下载图片并保存到指定文件夹中。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)