爬取猫和狗的图片各100张;在本地创建两个文件夹分别为cat和dog,将图片存入到相应文件夹。
时间: 2024-06-10 21:05:46 浏览: 8
好的,这是一个图片爬取和保存的任务。您可以使用Python的requests和BeautifulSoup库来爬取网页上的图片链接,再用Python的urllib库下载图片并存储到本地文件夹。
以下是示例代码,请先安装所需的库。
```
import requests
from bs4 import BeautifulSoup
import os
import urllib
# 爬取猫和狗的图片各100张
cat_url = "https://www.pinterest.com/search/pins/?q=cat&rs=typed&term_meta[]=cat%7Ctyped&term_meta[]=&page={}"
dog_url = "https://www.pinterest.com/search/pins/?q=dog&rs=typed&term_meta[]=dog%7Ctyped&term_meta[]=&page={}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0;Win64) AppleWebkit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
cat_count = 0
dog_count = 0
# 创建本地文件夹
if not os.path.exists('cat'):
os.mkdir('cat')
if not os.path.exists('dog'):
os.mkdir('dog')
# 爬取猫的图片
for i in range(1, 6):
url = cat_url.format(i)
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
images = soup.find_all('img')
for image in images:
try:
img_url = image.get('src')
if img_url.startswith('https://i.pinimg.com/'):
filename = os.path.join('cat', 'cat{}.jpg'.format(cat_count))
urllib.request.urlretrieve(img_url, filename)
print('Downloaded', filename)
cat_count += 1
if cat_count >= 100:
break
except Exception as e:
print(e)
# 爬取狗的图片
for i in range(1, 6):
url = dog_url.format(i)
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
images = soup.find_all('img')
for image in images:
try:
img_url = image.get('src')
if img_url.startswith('https://i.pinimg.com/'):
filename = os.path.join('dog', 'dog{}.jpg'.format(dog_count))
urllib.request.urlretrieve(img_url, filename)
print('Downloaded', filename)
dog_count += 1
if dog_count >= 100:
break
except Exception as e:
print(e)
print('Finished!')
```
运行代码后,程序将自动爬取100张猫图片和100张狗图片,并将它们存储在cat和dog文件夹中。注意:这些图片仅供学习和研究使用,任何其他违法用途均不被允许。
相关推荐
![](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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)