2022年 11月 5日

python批量下载文件

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

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

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

需要安装filetype包:pip install filetype

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Mon Feb 22 10:24:35 2021
  4. @author: weisssun
  5. """
  6. import requests
  7. import pandas as pd
  8. import filetype
  9. 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"}
  10. # 定义文件下载函数 downloadFile
  11. def downloadFile(url,savePath):
  12. # 将网页链接 url,文件夹路径 savePath 作为参数传入
  13. try:
  14. webPage = requests.get(url, headers = myHeaders, timeout=5)
  15. #print(webPage.status_code)
  16. # 获取网页
  17. webContent = webPage.content
  18. # 网页内容
  19. file_type = filetype.guess(webContent).extension
  20. # 识别文件类型
  21. #print(file_type)
  22. file_path = savePath + fileId + '.' + file_type
  23. # 根据文件夹路径、文件名id、文件类型,组合文件保存路径
  24. f = open(file_path, 'wb')
  25. f.write(webContent)
  26. # 将网页内容写入保存路径中
  27. f.close()
  28. except requests.exceptions.RequestException:
  29. print(fileId + '超时')
  30. # 读取excel表格
  31. data = pd.read_excel(r'D:\保存url和文件编号的文档.xlsx')
  32. #data = pd.read_excel(r'D:\保存url和文件编号的文档.xlsx', sheet_name='abc')
  33. # 下载文件保存文件夹
  34. savePath = 'D:/文件下载/'
  35. for i in data.index:
  36. fileId = str(data.loc[i, '编号'])
  37. url = str(data.loc[i, 'url'])
  38. if url == 'nan':
  39. continue
  40. else:
  41. downloadFile(url,savePath)