首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python爬虫入门:获取在百度图片搜索的时候第一页的所有图片并下载

python爬虫入门:获取在百度图片搜索的时候第一页的所有图片并下载

作者头像
V站CEO-西顾
发布2018-06-17 12:06:42
7640
发布2018-06-17 12:06:42
举报
文章被收录于专栏:V站V站

V站笔记

http://image.baidu.com/search/flip?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1460997499750_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=xxx

其中结尾的xxx代表要搜索的图片,比如:闪电侠等

  • 以下代码是,提醒要爬取什么图片之后,再自动下载采集,只采集其中的一页
# coding:utf8 import reimport requestsimport os name = input("请输入你想要的图片:") url = "http://image.baidu.com/search/flip?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1460997499750_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word={}".format(name) html = requests.get(url).text image_path = os.path.join(os.path.dirname(__file__),"images/{}".format(name)) pic_url = re.findall('"objURL":"(.*?)",',html,re.S) if not os.path.exists(image_path):    os.makedirs(image_path) i = 0for each in pic_url:    file_name = image_path + '/' + str(i) + '.jpg'    print(each)    try:        pic = requests.get(each,timeout=10)    except:        print('当前图片无法下载')        continue    f = open(file_name,'wb')    f.write(pic.content)    f.close()    i += 1
  • 上面的代码采用的是requests + re来获取到所有图片的链接,并下载,思路:
  1. requests获取到网页内容
  2. 用re正则来获取网页中图片的链接
  3. 再使用requests来下载图片
  • 注意
  1. 采用python3.6,python2的需要注意编码问题
  2. 如果没有requests包的话,请pip install requests安装

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档