zoukankan      html  css  js  c++  java
  • python 批量下载图片

    #coding=utf-8
    import re,sys
    import urllib

    def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html
    '''
    re.compile() 可以把正则表达式编译成一个正则表达式对象.
    re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。
    运行脚本将得到整个页面中包含图片的URL地址。
    '''

    def getImg(html):
    reg = r'src="(.+?.jpg)" pic_ext'
    imgre = re.compile(reg)
    imglist = re.findall(imgre,html)
    x = 0
    n = len(imglist)
    for imgurl in imglist:
    urllib.urlretrieve(imgurl,'/Users/newuser/zdx/python/img/%s.jpg' % x)
    sys.stdout.write(" 已下载:%.2f%%" % float((x+1)*100/n) + ' ')
    sys.stdout.flush()
    #不加sys.stdout.flush()只显示结束时的进度
    x+=1


    def callBack(*arg):
    print(arg);

    html = getHtml("http://tieba.baidu.com/p/2460150866")
    print "开始下载.."
    getImg(html)

    #这里的核心是用到了urllib.urlretrieve()方法,直接将远程数据下载到本地。

    '''
    urllib.urlretrieve(url, filename, reporthook=None,data=None)
    参数说明:
    url:外部或者本地url
    filename:指定了保存到本地的路径(如果未指定该参数,urllib会生成一个临时文件来保存数据);
    reporthook:是一个回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调。我们可以利用这个回调函数来显示当前的下载进度。
    data:指post到服务器的数据。该方法返回一个包含两个元素的元组(filename, headers),filename表示保存到本地的路径,header表示服务器的响应头。
    '''

  • 相关阅读:
    LeetCode-Read N Characters Given Read4 II
    LeetCode-One Edit Distance
    LeetCode-Palindrome Permutation II
    LeetCode- Longest Absolute File Path
    LeetCode-Strobogrammatic Number II
    LeetCode-Strobogrammatic Number
    LeetCode-Flatten 2D Vector
    LeetCode-Shortest Word Distance III
    LeetCode-Shortest Word Distance II
    Cookie/Session
  • 原文地址:https://www.cnblogs.com/cangqinglang/p/8624093.html
Copyright © 2011-2022 走看看