【问题标题】:AttributeError: 'module' object has no attribute 'urlretrieve'AttributeError:“模块”对象没有属性“urlretrieve”
【发布时间】:2013-07-31 10:06:52
【问题描述】:

我正在尝试编写一个程序,该程序将从网站上下载 mp3,然后将它们连接在一起,但每当我尝试下载文件时,都会出现此错误:

Traceback (most recent call last):
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 214, in <module> main()
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 209, in main getMp3s()
File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", line 134, in getMp3s
raw_mp3.add = urllib.urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
AttributeError: 'module' object has no attribute 'urlretrieve'

导致此问题的行是

raw_mp3.add = urllib.urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")

【问题讨论】:

    标签: python-3.x urllib attributeerror


    【解决方案1】:

    当您使用 Python 3 时,不再有 urllib 模块。它被分成了几个模块。

    这相当于urlretrieve:

    import urllib.request
    data = urllib.request.urlretrieve("http://...")
    

    urlretrieve 的行为方式与它在 Python 2.x 中的行为方式完全相同,因此可以正常工作。

    基本上:

    • urlretrieve 将文件保存到临时文件并返回一个元组(filename, headers)
    • urlopen 返回一个 Request 对象,其 read 方法返回一个包含文件内容的字节串

    【讨论】:

    【解决方案2】:

    假设您有以下代码行

    MyUrl = "www.google.com" #Your url goes here
    urllib.urlretrieve(MyUrl)
    

    如果您收到以下错误消息

    AttributeError: module 'urllib' has no attribute 'urlretrieve'
    

    那么你应该尝试下面的代码来解决这个问题:

    import urllib.request
    MyUrl = "www.google.com" #Your url goes here
    urllib.request.urlretrieve(MyUrl)
    

    【讨论】:

      【解决方案3】:

      兼容 Python 2+3 的解决方案是:

      import sys
      
      if sys.version_info[0] >= 3:
          from urllib.request import urlretrieve
      else:
          # Not Python 3 - today, it is most likely to be Python 2
          # But note that this might need an update when Python 4
          # might be around one day
          from urllib import urlretrieve
      
      # Get file from URL like this:
      urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
      

      【讨论】:

      • @tim654321 我改了。你是对的,这对于 Python 3 和更高版本来说可能是一样的。
      • 对您的评论的评论(“不是 Python 3...”):由于您正在检查 &gt;= 3,因此对 Python4 的关注是无效的。
      • @MartinR。或者更确切地说,...,关于 Python 4 的注释应该在 &gt;= 3 块中。
      猜你喜欢
      • 1970-01-01
      • 2010-11-18
      相关资源
      最近更新 更多