代码:

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