用python爬虫爬取百度图片
话不多说,直接上代码!
import requests
import re
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.61"}
def GetPictures(pic):
url = "https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%C3%A8&fr=ala&ala=1&alatpl=adress&pos=0&hs=2&xthttps=111111"
kw = {"word":pic}
response = requests.get(url,headers=headers,params=kw)
websites = re.findall('"objURL":"(.*?)"',response.content.decode('utf8'),re.DOTALL)
i = 0
for website in websites:
try:
response_web = requests.get(website,headers=headers)
if website[-3:]=='jpg':
with open("C:/Users/86135/Desktop/百度图片{}.jpg".format(i),'wb') as f:
f.write(response_web.content)
elif website[-4:]=='jpeg':
with open("C:/Users/86135/Desktop/百度图片{}.jpeg".format(i),'wb') as f:
f.write(response_web.content)
elif website[-3:]=='png':
with open("C:/Users/86135/Desktop/百度图片{}".format(i),'wb') as f:
f.write(response_web.content)
elif website[-3:]=='bmp':
with open("C:/Users/86135/Desktop/百度图片{}".format(i),'wb') as f:
f.write(response_web.content)
else:continue
except:continue
i+=1
if __name__ == '__main__':
pic = input("请输入您想要爬取的图片名称:")
GetPictures(pic)
运行结果如下: