AttributeError:'module'对象没有属性'urlretrieve'

Sik*_*217 64 urllib attributeerror python-3.x

我正在尝试编写一个程序,将从网站上下载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'
Run Code Online (Sandbox Code Playgroud)

导致此问题的线是

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

dom*_*om0 168

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

这相当于urlretrieve:

import urllib.request
data = urllib.request.urlretrieve("http://...")
Run Code Online (Sandbox Code Playgroud)

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

基本上:

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

  • 如果我想将 .mp3 文件下载到列表中,这仍然有效吗? (2认同)
  • 在使用谷歌的tensorflow机器学习教程(我是python的新手,所以你的答案非常感谢)时遇到这个错误http://www.tensorflow.org/tutorials/mnist/beginners/index.md (2认同)

Mar*_*oma 7

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")
Run Code Online (Sandbox Code Playgroud)


Ami*_*man 5

假设您有以下几行代码

MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
Run Code Online (Sandbox Code Playgroud)

如果您收到以下错误消息

AttributeError: module 'urllib' has no attribute 'urlretrieve'
Run Code Online (Sandbox Code Playgroud)

那么您应该尝试以下代码来解决该问题:

import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)
Run Code Online (Sandbox Code Playgroud)