【问题标题】:Python: handing exceptions when downloading non-existing files using urllibPython:使用 urllib 下载不存在的文件时处理异常
【发布时间】:2012-05-03 09:44:08
【问题描述】:

我知道如何使用 python 从 Web 下载文件,但是我希望处理所请求的文件不存在的情况。在这种情况下,我想打印一条错误消息(“404:找不到文件”)并且不向磁盘写入任何内容。但是,我仍然希望能够继续执行程序(即下载可能存在的列表中的其他文件)。

我该怎么做?下面是一些模板代码,用于根据其 url 下载文件(如果您认为有更好的方法,请随时修改它,但请保持简洁明了)。

import urllib
urllib.urlretrieve ("http://www.example.com/myfile.mp3", "myfile.mp3")

【问题讨论】:

    标签: python urllib2 urllib


    【解决方案1】:
    from urllib2 import URLError
    
    try:
        # your file request code here
    except URLError, e:
        if e.code == 404:
            # your appropriate code here
        else:
            # raise maybe?
    

    我关注了this 指南,它有一个特定的section about handling exceptions,发现它真的很有帮助。

    【讨论】:

      【解决方案2】:
      import urllib, urllib2
      try:
          urllib.urlretrieve ("http://www.example.com/", "myfile.mp3")
      except URLError, e:
          if e.code == 404:
              print "4 0 4"
          else:
              print "%s" % e 
      

      这就是您的代码所做的。它基本上试图检索 www.example.com 的网页并将其写入 myfile.mp3。它不会以异常结束,因为它不是在寻找 myfile.mp3,它基本上将它在 html 中获得的所有内容写入 myfile.mp3

      如果您正在寻找代码以在网络上的某个位置下载文件,请试试这个

      How do I download a zip file in python using urllib2?

      【讨论】:

        【解决方案3】:

        您的代码应如下所示:

        try:
            urllib.urlretrieve ("http://www.example.com/myfile.mp3", "myfile.mp3")
        except URLError,e:
            if e.code==404:
                print 'file not found. moving on...'
                pass
        

        【讨论】:

        • 据我所知,urllib.urlretrieve 不会在 404 响应中引发 URLError。如果域不好,它将引发 IOError。否则 myfile.mp3 将只包含 html 404 响应。
        猜你喜欢
        • 1970-01-01
        • 2011-06-13
        • 1970-01-01
        • 1970-01-01
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多