Python写一个图像采集
时间: 2024-02-16 12:03:33 浏览: 15
下面是一个使用Python的图像采集代码示例:
```python
import requests
from bs4 import BeautifulSoup
import os
# 定义目标网站的URL和存储图片的文件夹路径
url = 'https://unsplash.com/'
save_path = './images/'
# 创建存储图片的文件夹
if not os.path.exists(save_path):
os.makedirs(save_path)
# 发送请求并获取HTML页面
response = requests.get(url)
html = response.text
# 使用BeautifulSoup解析HTML页面
soup = BeautifulSoup(html, 'html.parser')
# 查找页面中所有图片的URL地址
img_tags = soup.find_all('img')
# 遍历所有图片URL,并下载图片到本地
for img_tag in img_tags:
img_url = img_tag.get('src')
if img_url.startswith('https://'):
img_name = img_url.split('/')[-1]
save_file_path = os.path.join(save_path, img_name)
img_data = requests.get(img_url).content
with open(save_file_path, 'wb') as f:
f.write(img_data)
print(f"已下载图片:{img_name}")
```
这个代码使用了requests库和BeautifulSoup库来发送HTTP请求和解析HTML页面。它首先定义了目标网站的URL和存储图片的文件夹路径。然后,它创建了存储图片的文件夹,发送请求并获取HTML页面。接下来,它使用BeautifulSoup解析HTML页面,并查找页面中所有图片的URL地址。最后,它遍历所有图片URL,并下载图片到本地。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)