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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

使用 tf.nn.dynamic_rnn 展开时间维度方式

使用 tf.nn.dynamic_rnn 展开时间维度方式

对于单个的 RNNCell , 使用色的 call 函数进行运算时 ,只是在序列时间上前进了一步 。如使用 x1、 ho 得到此h1, 通过 x2 、 h1 得到 h2 ...

Python最小二乘法矩阵

最小二乘法矩阵 #! /usr/bin/env python # -*- coding: utf-8 -*- import numpy as np def calc_left_k_m...

Python 获得命令行参数的方法(推荐)

本篇将介绍python中sys, getopt模块处理命令行参数 如果想对python脚本传参数,python中对应的argc, argv(c语言的命令行参数)是什么呢? 需要模块:sy...

Django中自定义模型管理器(Manager)及方法

1.自定义管理器(Manager) 在语句Book.objects.all()中, objects 是一个特殊的属性,通过它来查询数据库,它就是模型的一个Manager. 每...

go和python变量赋值遇到的一个问题

平时写得多的是python,最近看了一点go,今天碰到了一个问题,和大家分享一下 package main import "fmt" type student struct {...