python抓取网页中图片并保存到本地


Posted in Python onDecember 01, 2015

在上篇文章给大家分享PHP源码批量抓取远程网页图片并保存到本地的实现方法,感兴趣的朋友可以点击了解详情。

#-*-coding:utf-8-*- 
import os
import uuid
import urllib2
import cookielib
'''获取文件后缀名'''
def get_file_extension(file): 
  return os.path.splitext(file)[1] 
'''??建文件目录,并返回该目录'''
def mkdir(path):
  # 去除左右两边的空格
  path=path.strip()
  # 去除尾部 \符号
  path=path.rstrip("\\")
  if not os.path.exists(path):
    os.makedirs(path)
  return path
'''自动生成一个唯一的字符串,固定长度为36'''
def unique_str():
  return str(uuid.uuid1())
'''
抓取网页文件内容,保存到内存
@url 欲抓取文件 ,path+filename
'''
def get_file(url):
  try:
    cj=cookielib.LWPCookieJar()
    opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    urllib2.install_opener(opener)
    req=urllib2.Request(url)
    operate=opener.open(req)
    data=operate.read()
    return data
  except BaseException, e:
    print e
    return None
'''
保存文件到本地
@path 本地路径
@file_name 文件名
@data 文件内容
'''
def save_file(path, file_name, data):
  if data == None:
    return
  mkdir(path)
  if(not path.endswith("/")):
    path=path+"/"
  file=open(path+file_name, "wb")
  file.write(data)
  file.flush()
  file.close()
#获取文件后缀名
print get_file_extension("123.jpg");
#??建文件目录,并返回该目录
#print mkdir("d:/ljq")
#自动生成一个唯一的字符串,固定长度为36
print unique_str()
url="http://qlogo1.store.qq.com/qzone/416501600/416501600/100?0";
save_file("d:/ljq/", "123.jpg", get_file(url))

通过Python抓取指定Url中的图片保存至本地

# *** encoding: utf-8 ***
__author__='jiangyt'
""" 
fetch images from specific url
v1.0
""" 
import urllib, httplib, urlparse 
import re 
import random 
"""judge url exists or not""" 
def httpExists(url): 
  host, path = urlparse.urlsplit(url)[1:3] 
  if ':' in host: 
    # port specified, try to use it 
    host, port = host.split(':', 1) 
    try: 
      port = int(port) 
    except ValueError: 
      print 'invalid port number %r' % (port,) 
      return False 
  else: 
    # no port specified, use default port 
    port = None 
  try: 
    connection = httplib.HTTPConnection(host, port=port) 
    connection.request("HEAD", path) 
    resp = connection.getresponse( ) 
    if resp.status == 200: # normal 'found' status 
      found = True 
    elif resp.status == 302: # recurse on temporary redirect 
      found = httpExists(urlparse.urljoin(url,resp.getheader('location', ''))) 
    else: # everything else -> not found 
      print "Status %d %s : %s" % (resp.status, resp.reason, url) 
      found = False 
  except Exception, e: 
    print e.__class__, e, url 
    found = False 
  return found 
"""get html src,return lines[]""" 
def gGetHtmlLines(url): 
  if url==None : return 
  if not httpExists(url): return 
  try: 
    page = urllib.urlopen(url) 
    html = page.readlines() 
    page.close() 
    return html 
  except Exception, e: 
    print "gGetHtmlLines() error! Exception ==>>" + e 
    return 
"""get html src,return string""" 
def gGetHtml(url): 
  if url==None : return 
  if not httpExists(url): return 
  try: 
    page = urllib.urlopen(url) 
    html = page.read() 
    page.close() 
    return html 
  except Exception, e: 
    print "gGetHtml() error! Exception ==>>" + e 
    return 
"""根据url获取文件名""" 
def gGetFileName(url): 
  if url==None: return None 
  if url=="" : return "" 
  arr=url.split("/") 
  return arr[len(arr)-1] 
"""生成随机文件名""" 
def gRandFilename(type): 
  fname = '' 
  for i in range(16): 
    fname = fname + chr(random.randint(65,90)) 
    fname = fname + chr(random.randint(48,57)) 
  return fname + '.' + type 
"""根据url和其上的link,得到link的绝对地址""" 
def gGetAbslLink(url,link): 
  if url==None or link == None : return 
  if url=='' or link=='' : return url 
  addr = '' 
  if link[0] == '/' : 
    addr = gGetHttpAddr(url) + link 
  elif len(link)>3 and link[0:4] == 'http': 
    addr = link 
  elif len(link)>2 and link[0:2] == '..': 
    addr = gGetHttpAddrFatherAssign(url,link) 
  else: 
    addr = gGetHttpAddrFather(url) + link 
  return addr 
"""根据输入的lines,匹配正则表达式,返回list""" 
def gGetRegList(linesList,regx): 
  if linesList==None : return 
  rtnList=[] 
  for line in linesList: 
    matchs = re.search(regx, line, re.IGNORECASE) 
    if matchs!=None: 
      allGroups = matchs.groups() 
      for foundStr in allGroups: 
        if foundStr not in rtnList: 
          rtnList.append(foundStr) 
  return rtnList 
"""根据url下载文件,文件名参数指定""" 
def gDownloadWithFilename(url,savePath,file): 
  #参数检查,现忽略 
  try: 
    urlopen=urllib.URLopener() 
    fp = urlopen.open(url) 
    data = fp.read() 
    fp.close() 
    file=open(savePath + file,'w+b') 
    file.write(data) 
    file.close() 
  except IOError, error: 
    print "DOWNLOAD %s ERROR!==>>%s" % (url, error) 
  except Exception, e: 
    print "Exception==>>" + e 
"""根据url下载文件,文件名自动从url获取""" 
def gDownload(url,savePath): 
  #参数检查,现忽略 
  fileName = gGetFileName(url) 
  #fileName =gRandFilename('jpg') 
  gDownloadWithFilename(url,savePath,fileName) 
"""根据某网页的url,下载该网页的jpg""" 
def gDownloadHtmlJpg(downloadUrl,savePath): 
  lines= gGetHtmlLines(downloadUrl) # 'get the page source' 
  regx = r"""src\s*="?(\S+)\.jpg""" 
  lists =gGetRegList(lines,regx) #'get the links which match regular express' 
  if lists==None: return 
  for jpg in lists: 
    jpg = gGetAbslLink(downloadUrl, jpg) + '.jpg' 
    gDownload(jpg,savePath) 
    print gGetFileName(jpg) 
"""根据url取主站地址""" 
def gGetHttpAddr(url): 
  if url== '' : return '' 
  arr=url.split("/") 
  return arr[0]+"//"+arr[2] 
"""根据url取上级目录""" 
def gGetHttpAddrFather(url): 
  if url=='' : return '' 
  arr=url.split("/") 
  addr = arr[0]+'//'+arr[2]+ '/' 
  if len(arr)-1>3 : 
    for i in range(3,len(arr)-1): 
      addr = addr + arr[i] + '/' 
  return addr 
"""根据url和上级的link取link的绝对地址""" 
def gGetHttpAddrFatherAssign(url,link): 
  if url=='' : return '' 
  if link=='': return '' 
  linkArray=link.split("/") 
  urlArray = url.split("/") 
  partLink ='' 
  partUrl = '' 
  for i in range(len(linkArray)): 
    if linkArray[i]=='..': 
      numOfFather = i + 1 #上级数 
    else: 
      partLink = partLink + '/' + linkArray[i] 
  for i in range(len(urlArray)-1-numOfFather): 
    partUrl = partUrl + urlArray[i] 
    if i < len(urlArray)-1-numOfFather -1 : 
      partUrl = partUrl + '/' 
  return partUrl + partLink 
"""根据url获取其上的相关htm、html链接,返回list""" 
def gGetHtmlLink(url): 
  #参数检查,现忽略 
  rtnList=[] 
  lines=gGetHtmlLines(url) 
  regx = r"""href="?(\S+)\.htm""" 
  for link in gGetRegList(lines,regx): 
    link = gGetAbslLink(url,link) + '.htm' 
    if link not in rtnList: 
      rtnList.append(link) 
      print link 
  return rtnList 
"""根据url,抓取其上的jpg和其链接htm上的jpg""" 
def gDownloadAllJpg(url,savePath): 
  #参数检查,现忽略 
  gDownloadHtmlJpg(url,savePath) 
  #抓取link上的jpg 
  links=gGetHtmlLink(url) 
  for link in links: 
    gDownloadHtmlJpg(link,savePath) 
"""test""" 
def main(): 
  u='http://site.douban.com/196738/room/2462453/'#想要抓取图片的地址
  save='/root/python/tmp/' #图片所要存放的目录
  print 'download pic from [' + u +']' 
  print 'save to [' +save+'] ...' 
  gDownloadHtmlJpg(u,save) 
  print "download finished" 
if __name__ == "__main__":
  main()
else:
  print "called from intern."

以上代码是小编给大家介绍的python抓取网页中图片并保存到本地的全部内容,希望大家喜欢。

Python 相关文章推荐
python中assert用法实例分析
Apr 30 Python
解密Python中的描述符(descriptor)
Jun 03 Python
Python通过DOM和SAX方式解析XML的应用实例分享
Nov 16 Python
Python内建模块struct实例详解
Feb 02 Python
python实现名片管理系统
Nov 29 Python
Python玩转PDF的各种骚操作
May 06 Python
python openpyxl使用方法详解
Jul 18 Python
Pytorch之contiguous的用法
Dec 31 Python
使用Python实现将多表分批次从数据库导出到Excel
May 15 Python
Python3爬虫发送请求的知识点实例
Jul 30 Python
PyQt5的相对布局管理的实现
Aug 07 Python
Python中openpyxl实现vlookup函数的实例
Oct 28 Python
利用Python学习RabbitMQ消息队列
Nov 30 #Python
MySQL中表的复制以及大型数据表的备份教程
Nov 25 #Python
python基础知识小结之集合
Nov 25 #Python
python 多线程实现检测服务器在线情况
Nov 25 #Python
Python中time模块与datetime模块在使用中的不同之处
Nov 24 #Python
简单解决Python文件中文编码问题
Nov 22 #Python
Python制作简单的网页爬虫
Nov 22 #Python
You might like
星际争霸 Starcraft 编年史
2020/03/14 星际争霸
解析php中var_dump,var_export,print_r三个函数的区别
2013/06/21 PHP
PHP使用mysqldump命令导出数据库
2015/04/14 PHP
PHP制作用户注册系统
2015/10/23 PHP
详解PHP实现执行定时任务
2015/12/21 PHP
关于PHP5.6+版本“No input file specified”问题的解决
2019/12/11 PHP
JavaScript基本对象
2007/01/11 Javascript
可以把编码转换成 gb2312编码lib.UTF8toGB2312.js
2007/08/21 Javascript
jQuery的初始化与对象构建之浅析
2011/04/12 Javascript
jQuery Tools tab使用介绍
2012/07/14 Javascript
jquery ajax提交整个表单元素的快捷办法
2013/03/27 Javascript
用js实现in_array的方法
2013/11/05 Javascript
JS的参数传递示例介绍
2014/02/08 Javascript
javascript数据类型示例分享
2015/01/19 Javascript
JS实现FLASH幻灯片图片切换效果的方法
2015/03/04 Javascript
jquery实现页面虚拟键盘特效
2015/08/08 Javascript
jquery.Jcrop结合JAVA后台实现图片裁剪上传实例
2016/11/05 Javascript
Angular.JS通过指令操作DOM的方法
2017/05/10 Javascript
微信JSSDK调用微信扫一扫功能的方法
2017/07/25 Javascript
使用socket.io制做简易WEB聊天室
2018/01/02 Javascript
关于vue中watch检测到不到对象属性的变化的解决方法
2018/02/08 Javascript
jQuery常见的遍历DOM操作详解
2018/09/05 jQuery
js for终止循环 跳出多层循环
2018/10/04 Javascript
Vue2.X和Vue3.0数据响应原理变化的区别
2019/11/07 Javascript
浅谈python多线程和队列管理shell程序
2015/08/04 Python
详解Python Socket网络编程
2016/01/05 Python
详解Python发送email的三种方式
2018/10/18 Python
Python零基础入门学习之输入与输出
2019/04/03 Python
python opencv实现图片缺陷检测(讲解直方图以及相关系数对比法)
2020/04/07 Python
Python ellipsis 的用法详解
2020/11/20 Python
加拿大女装网上购物:Reitmans
2016/10/20 全球购物
Chemist Warehouse官方海外旗舰店:澳洲第一连锁大药房
2017/08/25 全球购物
小学优秀辅导员事迹材料
2014/05/11 职场文书
小学生常见病防治方案
2014/06/06 职场文书
教育实习指导教师评语
2014/12/31 职场文书
导游词之苏州寒山寺
2019/12/05 职场文书