utils_20.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. def down_file(url, name, path):
  2. if os.path.exists(path):
  3. return
  4. print("开始下载:" + name + ".mp3")
  5. headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  6. "Accept-Encoding": "gzip, deflate, br",
  7. "Accept-Language": "zh-CN,zh;q=0.9",
  8. "Upgrade-Insecure-Requests": "1",
  9. 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
  10. count = 0
  11. while count < 3:
  12. try:
  13. r = requests.get(url, headers=headers, stream=True, timeout=60)
  14. # print(r.status_code)
  15. if (r.status_code == 200):
  16. with open(path, "wb+") as f:
  17. for chunk in r.iter_content(1024):
  18. f.write(chunk)
  19. print("完成下载:" + name + ".mp3")
  20. break
  21. except Exception as e:
  22. print(e)
  23. print("下载出错:" + name + ".mp3,3秒后重试")
  24. if os.path.exists(path):
  25. os.remove(path)
  26. time.sleep(3)
  27. count += 1
  28. pass