Python 下载器

2 投票
5 回答
1380 浏览
提问于 2025-04-16 06:31

我正在尝试用Python写一个脚本来下载图片文件,我在网上找到了这个方法,但每次下载的图片都是“损坏”的。有没有什么建议...

def download(url):
 """Copy the contents of a file from a given URL
 to a local file.
 """
 import urllib
 webFile = urllib.urlopen(url)
 localFile = open(url.split('/')[-1], 'w')
 localFile.write(webFile.read())
 webFile.close()
 localFile.close()

补充:代码的格式没有很好地保留缩进,但我可以保证缩进是存在的,这不是我的问题。

5 个回答

3

如果你想写一个二进制文件,记得要加上'b'这个标志。第7行应该改成:

localFile = open(url.split('/')[-1], 'wb')

虽然这段代码现在不一定要这样写,但将来你可以考虑:

  • 在函数外部导入需要的库,这样更整洁。
  • 用os.path.basename来获取路径的文件名,而不是用字符串解析的方法。
  • 使用with语句来处理文件,这样就不用手动关闭文件了。这会让你的代码更简洁,而且如果代码出现错误,文件也能被正确关闭。

我会把你的代码改成:

import urllib
import os.path

def download(url):
 """Copy the contents of a file from a given URL
 to a local file in the current directory.
 """
 with urllib.urlopen(url) as webFile:
  with open(os.path.basename(url), 'wb') as localFile:
   localFile.write(webFile.read())
6

你可以简单地这样做

urllib.urlretrieve(url, filename)

这样可以让你省去很多麻烦。

5

你需要以二进制模式打开本地文件:

localFile = open(url.split('/')[-1], 'wb')

否则,文件中的换行符会被搞乱,导致文件损坏。

撰写回答