Press ESC to close

python实现图片下载自动分类

代码:

import urllib.request
from httpx import request
import requests
import os

def download_image_improved(search_key,url):
  #伪造headers信息
  headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"}
  #限定URL
  url = url
  response = requests.get(url, headers=headers, stream=True)
  from contextlib import closing
  #用完流自动关掉
  with closing(requests.get(url, headers=headers, stream=True)) as response:
    #打开文件
    img_name=url.split('/')[5]
    save_file_path=os.getcwd()+'\images\'+search_key +'\'
    if not os.path.exists(save_file_path):
        os.mkdir(save_file_path)
    save_file_name=save_file_path+img_name
    
    with open(save_file_name, 'wb') as fd:
      #每128写入一次
      for chunk in response.iter_content(128):
        fd.write(chunk)
      print("下载图片到这里了:"+save_file_name)
      
from pexels_api import API
PEXELS_API_KEY = 'xxx'
api = API(PEXELS_API_KEY)
search_key='Snow lotus fruit'
api.search(search_key, page=1, results_per_page=20)
photos = api.get_entries()
for photo in photos:
  print('Photo original size: ', photo.original)
  download_image_improved(search_key,photo.original)

发表回复