• 如何通过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()方法,将远程数据下载到本地,并重新命名!

  • 相关阅读:
    【C++杂货铺】国庆中秋特辑——多态由浅入深详细总结
    《动手学深度学习 Pytorch版》 7.2 使用块的网络(VGG)
    tinyxml2开源库使用
    Spirng,SpringBoot实现多文件上传(MultipartFile)
    爬虫-浏览器自动化
    2024携程校招面试真题汇总及其解答(一)
    【Lua】脚本入门
    互联网商业模式之全民拼购
    一篇文章带你彻底搞懂wait/notify
    基于关联规则的网络信息安全风险度量分析模型
  • 原文地址:https://blog.csdn.net/oldboyedu1/article/details/127848374