python实现下载指定网址所有图片的方法

所属分类: 脚本专栏 / python 阅读数: 759
收藏 0 赞 0 分享

本文实例讲述了python实现下载指定网址所有图片的方法。分享给大家供大家参考。具体实现方法如下:

#coding=utf-8
#download pictures of the url
#useage: python downpicture.py www.baidu.com
import os
import sys
from html.parser import HTMLParser
from urllib.request import urlopen
from urllib.parse import urlparse
def getpicname(path):
  '''  retrive filename of url    '''
  if os.path.splitext(path)[1] == '':
    return None
  pr=urlparse(path)
  path='http://'+pr[1]+pr[2]
  return os.path.split(path)[1]
def saveimgto(path, urls):
  '''
  save img of url to local path
  '''
  if not os.path.isdir(path):
    print('path is invalid')
    sys.exit()
  else:
    for url in urls:
      of=open(os.path.join(path, getpicname(url)), 'w+b')
      q=urlopen(url)
      of.write(q.read())
      q.close()
      of.close()
class myhtmlparser(HTMLParser):
  '''put all src of img into urls'''
  def __init__(self):
    HTMLParser.__init__(self)
    self.urls=list()
    self.num=0
  def handle_starttag(self, tag, attr):
    if tag.lower() == 'img':
      srcs=[u[1] for u in attr if u[0].lower() == 'src']
      self.urls.extend(srcs)
      self.num = self.num+1
if __name__ == '__main__':
  url=sys.argv[1]
  if not url.startswith('http://'):
    url='http://' + sys.argv[1]
  parseresult=urlparse(url)
  domain='http://' + parseresult[1]
  q=urlopen(url)
  content=q.read().decode('utf-8', 'ignore')
  q.close()
  myparser=myhtmlparser()
  myparser.feed(content)
  for u in myparser.urls:
    if (u.startswith('//')):
      myparser.urls[myparser.urls.index(u)]= 'http:'+u
    elif u.startswith('/'):
      myparser.urls[myparser.urls.index(u)]= domain+u
  saveimgto(r'D:\python\song', myparser.urls)
  print('num of download pictures is {}'.format(myparser.num))

运行结果如下:

num of download pictures is 19

希望本文所述对大家的Python程序设计有所帮助。

更多精彩内容其他人还在看

Python实现图像几何变换

这篇文章主要介绍了Python实现图像几何变换的方法,实例分析了Python基于Image模块实现图像翻转、旋转、改变大小等操作的相关技巧,非常简单实用,需要的朋友可以参考下
收藏 0 赞 0 分享

Python中的urllib模块使用详解

这篇文章主要介绍了Python中的urllib模块使用详解,是Python入门学习中的基础知识,需要的朋友可以参考下
收藏 0 赞 0 分享

Python的多态性实例分析

这篇文章主要介绍了Python的多态性,以实例形式深入浅出的分析了Python在面向对象编程中多态性的原理与实现方法,需要的朋友可以参考下
收藏 0 赞 0 分享

python生成IP段的方法

这篇文章主要介绍了python生成IP段的方法,涉及Python文件读写及随机数操作的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

python操作redis的方法

这篇文章主要介绍了python操作redis的方法,包括Python针对redis的连接、设置、获取、删除等常用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

python妹子图简单爬虫实例

这篇文章主要介绍了python妹子图简单爬虫,实例分析了Python爬虫程序所涉及的页面源码获取、进度显示、正则匹配等技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

分析用Python脚本关闭文件操作的机制

这篇文章主要介绍了分析用Python脚本关闭文件操作的机制,作者分Python2.x版本和3.x版本两种情况进行了阐述,需要的朋友可以参考下
收藏 0 赞 0 分享

python实现搜索指定目录下文件及文件内搜索指定关键词的方法

这篇文章主要介绍了python实现搜索指定目录下文件及文件内搜索指定关键词的方法,可实现针对文件夹及文件内关键词的搜索功能,需要的朋友可以参考下
收藏 0 赞 0 分享

python中getaddrinfo()基本用法实例分析

这篇文章主要介绍了python中getaddrinfo()基本用法,实例分析了Python中使用getaddrinfo方法进行IP地址解析的基本技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

python查找指定具有相同内容文件的方法

这篇文章主要介绍了python查找指定具有相同内容文件的方法,涉及Python针对文件操作的相关技巧,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多