Python Urlretrieve从变量中提供本地_文件名

Python Urlretrieve从变量中提供本地_文件名,python,python-2.7,urlopen,Python,Python 2.7,Urlopen,我有一个非常恼人的问题 我正在使用Python打开一个URL链接,它是一个pdf文件,我想把它保存在我的本地文件夹中 我的代码: urlPath = 'http://example.com/test.pdf' myFile = urlopen(urlPath) urllib.urlretrieve(myFile.url, myFile.url) 错误消息: tfp = open(filename, 'wb') IOError: [Errno 22] invalid mode ('wb') or

我有一个非常恼人的问题

我正在使用Python打开一个URL链接,它是一个pdf文件,我想把它保存在我的本地文件夹中

我的代码:

urlPath = 'http://example.com/test.pdf'
myFile = urlopen(urlPath)
urllib.urlretrieve(myFile.url, myFile.url)
错误消息:

tfp = open(filename, 'wb')
IOError: [Errno 22] invalid mode ('wb') or filename: 
我试着使用下面的代码,一切都很好,我的文件存储正确

urlPath = 'http://example.com/test.pdf'
myFile = urlopen(urlPath)
urllib.urlretrieve(myFile.url, 'myFile.pdf')

我写错了什么?

您只需要urlretrieve的第二个参数的文件名,而不是整个URL。你可以做:

filename = myFile.url.rsplit('/', 1)

然后打电话

urllib.urlretrieve(myFile.url, filename)
您可以使用,这里是(1)如果url有一个查询部分,例如
/path/test.pdf?version=1.2
(2)它对unicode名称的支持很差,例如,它将
u'Δοκιμή.pdf'
保存为
'%CE%B4%CE%BF%CE%BA%CE%B9%CE%BC%CE%CE%AE.pdf'
(3)它可能尝试转义当前文件夹(如果
unquote()
使用不小心):
“..%5Ctest.pdf”
urllib.urlretrieve(myFile.url, filename)