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设计】。

相关文章

Python用list或dict字段模式读取文件的方法

前言 Python用于处理文本数据绝对是个利器,极为简单的读取、分割、过滤、转换支持,使得开发者不需要考虑繁杂的流文件处理过程(相对于JAVA来说的,嘻嘻)。博主自己工作中,一些复杂的文...

Python利用Beautiful Soup模块搜索内容详解

前言 我们将利用 Beautiful Soup 模块的搜索功能,根据标签名称、标签属性、文档文本和正则表达式来搜索。 搜索方法 Beautiful Soup 内建的搜索方法如下:...

基于Python socket的端口扫描程序实例代码

本文研究的主要是Python的端口扫描程序,具体实例代码如下。 先来看看第一个端口扫描程序代码,获取本机的IP和端口号: import socket def get_my_ip...

Python 串口读写的实现方法

Python 串口读写的实现方法

1.安装pyserial https://pypi.python.org/pypi/pyserial Doc:http://pythonhosted.org/pyserial/ 使用Py...

python类型强制转换long to int的代码

python2.4版本以后,如果int的值超出范围不会溢出,而是内部转换为long,在网上没有找到从long型强制转换成int的代码,这里所说的int取值范围是和java里一致,即用四个...