为什么我不能用下载图片urllib.urlretrieve?

2024-10-03 17:16:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用

import os, urllib
folderName = 'downloadedImages'
if not os.path.exists(folderName):
  os.makedirs(folderName)
urllib.urlretrieve(https://www.google.com/images/srpr/logo3w.png, './' + folderName + '/')

但是,我收到一个错误:IOError: [Errno 21] Is a directory: './downloadedImages/'。在

为什么?在


Tags: pathhttpsimportcomifoswwwexists
3条回答

因为错误说明:在第二个参数中提供的是一个目录。它必须是本地(目标)文件名。在

python docs状态(强调我的):

The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name).

urllib.urlretrieve()的第二个参数需要文件名,而不是目录。在

检查文档:http://docs.python.org/library/urllib.html#urllib.urlretrieve

您需要提供文件名,而不是目录路径:

urllib.urlretrieve("path/to/resource", os.path.join(folderName, "filename.jpg"))

相关问题 更多 >