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

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Django集成搜索引擎Elasticserach的方法示例

1.背景 当用户在搜索框输入关键字后,我们要为用户提供相关的搜索结果。可以选择使用模糊查询 like 关键字实现,但是 like 关键字的效率极低。查询需要在多个字段中进行,使用 li...

python截取两个单词之间的内容方法

1. __init__ 初始化文件路径,关键字1,关键字2; 2. key_match 使用with open 方法,以二进制方式(也可以改成utf-8,GB2312)读取文件内容(支持...

python 实现对文件夹中的图像连续重命名方法

python实现的对文件夹中的图像进行连续的重命名方法: import os class BatchRename(): def __init__(self): self.pa...

python互斥锁、加锁、同步机制、异步通信知识总结

某个线程要共享数据时,先将其锁定,此时资源的状态为“锁定”,其他线程不能更改;直到该线程释放资源,将资源的状态变成“非锁定”,其他的线程才能再次锁定该资源。互斥锁保证了每次只有一个线程进...

Python collections模块使用方法详解

Python collections模块使用方法详解

一、collections模块 1.函数namedtuple (1)作用:tuple类型,是一个可命名的tuple (2)格式:collections(列表名称,列表) (3)̴...