用python爬虫爬取百度图片

用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)

运行结果如下:
在这里插入图片描述
在这里插入图片描述

  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值