import requests
import json
import uuid
from urllib import parse
#模仿浏览器的请求头#请求头
headers={'Referer':'https://image.baidu.com/search/index?tn=b''aiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=''%E5%90%B4%E9%9D%92%E5%B3%B0','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebK''it/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 S''afari/537.36 Edg/85.0.564.51','X-Requested-With':'XMLHttpRequest'}
(2)写get_html函数、download函数
#请求函数defget_html(url):
html=requests.get(url,headers=headers)if html.status_code==200:# print('ok')
res=html.json()['data']for r in res:if r:print(r['thumbURL'])#得到url
download(r['thumbURL'])
result = html.json()else:print('error')#download函数defdownload(url):
img=requests.get(url)withopen('img/{}.jpg'.format(uuid.uuid4()),'wb')as f:
chunks=img.iter_content(125)for c in chunks:
f.write(c)