urllib.request for python 3.3无法下载文件

use*_*101 2 python download python-3.x

我想用python下载一个大型存档文件并保存它,但是urllib对我不起作用.这是我的代码:

    import urllib
    urllib.request("http://www.petercollingridge.co.uk/sites/files/peter/particle_tutorial_7.txt")
Run Code Online (Sandbox Code Playgroud)

请注意,我在此示例中使用的链接不是大型存档.我只是以它为例.它直接链接到.txt文件,因此它应该工作.我收到此错误:

    Traceback (most recent call last):
    File "<pyshell#11>", line 1, in <module>
    urllib.request("http://www.petercollingridge.co.uk/sites/files/peter/particle_tutorial_7.txt")
    AttributeError: 'module' object has no attribute 'request'
Run Code Online (Sandbox Code Playgroud)

在我看来,urllib在某种程度上被打破并缺少"请求"方法.我使用的是Python 3.3.我应该使用其他模块还是实际上是Python问题?

Chr*_*isP 14

不,它没有被打破. urllib.request文件是如何工作的很清楚:

import urllib.request
req = urllib.request.urlopen('http://www.google.com')
data = req.read()
Run Code Online (Sandbox Code Playgroud)

编辑:如果您需要将文件直接写入磁盘而不是处理数据,请使用urlretrieve.

urllib.request.urlretrieve('http://example.com/big.zip', 'file/on/disk.zip')
Run Code Online (Sandbox Code Playgroud)

  • 根据手册,`urlretrieve`*可能在将来某个时候被弃用*.是否存在直接保存到文件的未来安全方法? (4认同)
  • 注意:*“我想用python下载一个大的存档文件并保存”*。如果你想下载一个可能不适合内存的大文件,`req.read()` 是不合适的。你可以使用 [`urlretrieve()` 代替](http://stackoverflow.com/a/20716205/4279) (2认同)