打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
如何通过Python进行图片批量下载?

  大家在上网冲浪的时候,看到喜欢的图片都想要保存下来,有的时候可以直接右键图片另存为,但有的时候图片是无法下载的,甚至需要跳转到其他的网页去,非常麻烦。这篇文章教大家用Python下载图片,那么如何利用Python实现简单的图片下载?具体请看下文。

  一、页面抓取

  #coding=utf-8

  import urllib

  def getHtml(url):

  page = urllib.urlopen(url)

  html = page.read()

  return html

  html = getHtml("https://tieba.baidu.com/p/5582243679")

  print html

  页面数据抓取过程定义了getHtml()函数,其作用是给getHtml()传递一个网址,最终进行整个页面的下载。

  二、页面数据筛选

  import re

  import urllib

  def getHtml(url):

  page = urllib.urlopen(url)

  html = page.read()

  return html

  def getImg(html):

  reg = r'src="(.+?\.jpg)" pic_ext'

  imgre = re.compile(reg)

  imglist = re.findall(imgre,html)

  return imglist

  html = getHtml("https://tieba.baidu.com/p/5582243679")

  print getImg(html)

  页面数据筛选中,定义了一个新的函数getImg(),该函数的功能是筛选出.jpg格式的图片地址。

  三、图片下载

  #coding=utf-8

  import urllib

  import re

  def getHtml(url):

  page = urllib.urlopen(url)

  html = page.read()

  return html

  def getImg(html):

  reg = r'src="(.+?\.jpg)" pic_ext'

  imgre = re.compile(reg)

  imglist = re.findall(imgre,html)

  x = 0

  for imgurl in imglist:

  urllib.urlretrieve(imgurl,'%s.jpg' % x)

  x+=1

  html = getHtml("https://tieba.baidu.com/p/5582243679")

  print getImg(html)

  通过for循环获得所有符合条件的图片网址,并采用urllib.urlretrieve()方法,将远程数据下载到本地,并重新命名!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python爬图
Python小程序自动爬取站酷网首页的照片
Crawler:反爬虫之基于urllib库+伪装浏览器方式实现从各种网站上(以百度贴吧为例)获得你喜欢的照片下载到本地电脑上
Python爬虫:股票数据爬取
用python实现的抓取腾讯视频所有电影的爬虫
自如租房
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服