python下载图片实现方法(超简单)

yipeiwu_com6年前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("/zb_users/upload/202003/xjz5nppsqni.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()方法,将远程数据下载到本地,并重新命名!

以下是补充

如下所示:

import urllib.request
response = urllib.request.urlopen('//www.jb51.net/g/500/600')
cat_img = response.read()

with open('cat_500_600.jpg','wb') as f:
 f.write(cat_img)

urlopen()括号里既可以是一个字符串也可以是一个request对象,当传入字符串的时候会转换成一个request对象,因此代码

response = urllib.request.urlopen('//www.jb51.net/g/500/600') 也可以写成

req = urllib.request.Request('//www.jb51.net/g/500/600')

1、response = urllib.request.urlopen(req)
2、responce还有geturl,info,getcode方法

代码with open('cat_500_600.jpg','wb') as f:

f.write(cat_img)等价于

1、f = open('cat_500_600.jpg','wb')

2、try:

3、 data = f.write(cat_img)

4、finally:

5、 f.close()

以上这篇python下载图片实现方法(超简单)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在IPython中执行Python程序文件的示例

简单使用了一下之后,我觉得如果有机会(公司里面编码是极不自由的,也无所谓,我在公司不做数据分析),我肯定是更喜欢使用IPython作为我的Python shell环境了。简单的接触发现了...

python自动化实现登录获取图片验证码功能

python自动化实现登录获取图片验证码功能

主要记录一下:图片验证码 1.获取登录界面的图片 2.获取验证码位置 3.在登录页面截取验证码保存 4.调用百度api识别(目前准确率较高的识别图片api) 本次登录的系统页面,可以看到...

Python实现运行其他程序的四种方式实例分析

Python实现运行其他程序的四种方式实例分析

本文实例讲述了Python实现运行其他程序的四种方式。分享给大家供大家参考,具体如下: 在Python中,可以方便地使用os模块来运行其他脚本或者程序,这样就可以在脚本中直接使用其他脚本...

在matplotlib的图中设置中文标签的方法

在matplotlib的图中设置中文标签的方法

其实就是通过 FontProperties来设置的,请参考以下代码: import matplotlib.pyplot as plt from matplotlib.font_man...

windows下python虚拟环境virtualenv安装和使用详解

前面介绍了python在ubuntu16.04环境下,python的虚拟环境virtualenv的安装,下面介绍在windows环境下的安装和使用。 环境信息 操作系统:windo...