python批量下载文件

在已经有文件url的前提下,批量下载文件。

在excel文档中,保存url和文件名/编号。

request读取网页内容,filetype判断文件类型,批量下载保存。

需要安装filetype包:pip install filetype

# -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 10:24:35 2021

@author: weisssun
"""
import requests
import pandas as pd
import filetype

myHeaders = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"}

# 定义文件下载函数 downloadFile

def downloadFile(url,savePath):
    # 将网页链接 url,文件夹路径 savePath 作为参数传入
    try:
        webPage = requests.get(url, headers = myHeaders, timeout=5)
        #print(webPage.status_code)
        # 获取网页
        webContent = webPage.content
        # 网页内容
        file_type = filetype.guess(webContent).extension
        # 识别文件类型
        #print(file_type)
        file_path = savePath + fileId + '.' + file_type
        # 根据文件夹路径、文件名id、文件类型,组合文件保存路径
        f = open(file_path, 'wb')
        f.write(webContent)
        # 将网页内容写入保存路径中
        f.close()
    except requests.exceptions.RequestException:
        print(fileId + '超时')

# 读取excel表格
        
data = pd.read_excel(r'D:\保存url和文件编号的文档.xlsx')
#data = pd.read_excel(r'D:\保存url和文件编号的文档.xlsx', sheet_name='abc')

# 下载文件保存文件夹
savePath = 'D:/文件下载/'

for i in data.index:
    fileId = str(data.loc[i, '编号'])
    url = str(data.loc[i, 'url'])
    if url == 'nan':
        continue
    else:
        downloadFile(url,savePath)
    
  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值