代码:
import urllib.request from httpx import request import requests import os def download_image_improved(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_name=os.getcwd()+'\images\'+img_name with open(save_file_name, 'wb') as fd: #每128写入一次 for chunk in response.iter_content(128): fd.write(chunk) from pexels_api import API PEXELS_API_KEY = 'xxxxx' api = API(PEXELS_API_KEY) search_key='onion' api.search(search_key, page=1, results_per_page=5) photos = api.get_entries() for photo in photos: print('Photo original size: ', photo.original) download_image_improved(photo.original)