使用python编写程序实现要求程序(1)能接受至少2个网址的输入,并使用urllib模块从这些提供的网址上(2)下载20张以上包含猫、狗、熊猫等动物图片,(3)将其中是猫的图片保存在磁盘上(提示:可通过重命名图片),(4)并输出一共下载了多少图片、保存了多少张猫的图片、保存的图片位置的统计数据。
时间: 2023-06-24 18:08:25 浏览: 81
以下是实现以上要求的Python程序:
```python
import urllib.request
import os
import re
def download_images(url, animal, count):
opener = urllib.request.urlopen(url)
html_content = opener.read().decode('utf-8')
img_urls = re.findall('img .*?src="(.*?)"', html_content)
downloaded_images = 0
cat_images = 0
for img_url in img_urls:
if downloaded_images >= count:
break
if animal in img_url:
cat_images += 1
filename = os.path.basename(img_url)
urllib.request.urlretrieve(img_url, 'cat_' + filename)
else:
filename = os.path.basename(img_url)
urllib.request.urlretrieve(img_url, filename)
downloaded_images += 1
return downloaded_images, cat_images
if __name__ == '__main__':
urls = ['https://www.pexels.com/search/cat/', 'https://www.pexels.com/search/dog/']
animal = 'cat'
download_count = 20
total_downloaded_images = 0
total_cat_images = 0
for url in urls:
downloaded_images, cat_images = download_images(url, animal, download_count)
total_downloaded_images += downloaded_images
total_cat_images += cat_images
print('Total downloaded images:', total_downloaded_images)
print('Total cat images:', total_cat_images)
print('Images saved in:', os.getcwd())
```
在程序中,我们首先定义了一个函数 `download_images`,用于从给定的URL中下载指定数量的图片,并保存猫的图片。该函数使用了 `urllib` 模块来下载图片,并使用正则表达式从HTML内容中提取出图片的URL。如果下载的图片是猫的图片,则将其保存在磁盘上,并重命名为 `cat_` 开头的文件名。
在主程序中,我们定义了要下载的图片的数量和要下载的网址。然后,我们依次下载每个网址中的图片,并统计下载的图片总数、保存的猫的图片总数以及图片保存的位置。
注意:该程序在运行时需要联网才能下载图片。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)