【问题标题】:How to exclude 404 pages from python downloading如何从python下载中排除404页面
【发布时间】:2020-10-17 16:52:44
【问题描述】:

此代码运行良好,但如何阻止 404 页面下载? Urllib 请求总是返回 403,因为主机不允许 python。有没有其他方法可以检测文件是否存在?

import requests
import os
while True:
  id = input("Enter ID:")
  if os.path.exists("1.mp3"):
    os.remove("1.mp3")
  url = 'http://www.texture.ml/kcl/{0}.mp3'.format(id)
  r = requests.get(url)
  with open("1.mp3", 'wb') as f:
    f.write(r.content)

【问题讨论】:

    标签: python python-requests urllib2


    【解决方案1】:

    您只需为其添加一张支票。例如

    import requests
    import os
    while True:
      id = input("Enter ID:")
      if os.path.exists("1.mp3"):
        os.remove("1.mp3")
      url = 'http://www.texture.ml/kcl/{0}.mp3'.format(id)
      r = requests.get(url)
      if r.status_code != 404:
        with open("1.mp3", 'wb') as f:
          f.write(r.content)
    

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 2019-02-09
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 2019-04-28
      相关资源
      最近更新 更多