用Python语言编写爬取百度图片中猫和狗的图片各100张,将图片存入相应文件夹,两个文件夹分别为cat和dog的代码
时间: 2024-06-10 14:04:44 浏览: 36
import requests
import os
def download_image(url, path):
r = requests.get(url)
with open(path, 'wb') as f:
f.write(r.content)
def download_images(keyword, category, num):
if not os.path.exists(category):
os.makedirs(category)
url = f'https://www.baidu.com/s?tn=image&word={keyword}&pn='
for i in range(0, num, 30):
r = requests.get(url+str(i))
for j in range(30):
try:
index = i+j
img_url = r.json()['imgs'][j]['objURL']
download_image(img_url, f"{category}/{keyword}_{index}.jpg")
except:
pass
if __name__ == '__main__':
download_images('猫', 'cat', 100)
download_images('狗', 'dog', 100)
阅读全文