Python利用文本保存的链接批量下载不存在的文件

版权声明:zhaojanc https://blog.csdn.net/qq_38641985/article/details/84883045
import urllib 
import urllib2 
import requests
import random 
import uuid,os


my_headers={
    "User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36",
    'Referer':'http://m.mzitu.com/15309'}


def read_txt(path):
    
    mt=[]
    f=open(path,'r')
    for t in f.readlines():
        mt.append(t)
    f.close()
    return mt
 
def down_load(img,my_headers):
    path_name=img.split('/')[-1]
    path_name=path_name.replace('\n','')
    new_name="pic/" + path_name
    if not os.path.exists(new_name):
        request =  urllib2.Request(url=img, headers=my_headers)
        response = urllib2.urlopen(request)
        pic=response.read()
        path_name=img.split('/')[-1]
        path_name=path_name.replace('\n','')
        with open("%s" % new_name, "wb") as f:
            f.write(pic)
        
    print "downloading with urllib=======>",new_name 
    
def main():
    path="data.txt"
    mt=read_txt(path)
    for f in mt:
        down_load(f,my_headers)
    print 'fininsh'.center(40,'-')
    
main()

data.txt
运行前请手动先建立一个pic目录

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_38641985/article/details/84883045