python3下载图片

import urllib.request  
import socket  
import re  
import sys  
import os

targetDir = r"E:\DATA常用py脚本" 

def destFile(path):  
    if not os.path.isdir(targetDir):  
        os.mkdir(targetDir)  
    pos = path.rindex('/')  
    t = os.path.join(targetDir, path[pos+1:])  
    return t  
  

if __name__ == "__main__":  
    hostname = "http://www.douban.com"  
    req = urllib.request.Request(hostname)  
    webpage = urllib.request.urlopen(req)  
    html = webpage.read()  


    #s:任意空白字符
    #^:匹配字符串的开头
    #*:匹配前一个字符0次或无数次
    #?:匹配前一个字符0次或1次

    result=re.findall(r'(https:[^s]*?(jpg|png|gif))', str(html))
    #print(result)

    for link, t in result:  
        #print(link,t)  
        urllib.request.urlretrieve(link, destFile(link)) 
原文地址:https://www.cnblogs.com/dengyg200891/p/6059383.html