Python httplib/urllib获取文件名

13

有没有可能获取文件名

e.g. xyz.com/blafoo/showall.html

如果您使用urllib或httplib?

这样我就可以将文件保存在服务器上的文件名下了吗?

如果您访问类似于的网站

xyz.com/blafoo/ 

您无法看到文件名。

谢谢


可能是 urllib2 file name 的重复问题。 - KevinDTimm
4个回答

31

从响应的 HTTP 头中获取文件名:

import cgi

response = urllib2.urlopen(URL)
_, params = cgi.parse_header(response.headers.get('Content-Disposition', ''))
filename = params['filename']

从URL中获取文件名:

import posixpath
import urlparse 

path = urlparse.urlsplit(URL).path
filename = posixpath.basename(path)

很好的答案,只需要微小的修正。使用os.path.basename(path)是一种跨平台的实现方式。 - Jorge Vargas
3
@JorgeVargas:不是使用os.path模块,而是应该使用posixpath模块。如果您不能理解为什么,请问我,我会详细说明。请注意,这里使用os.path是错误的。 - jfs
1
我会问:为什么应该使用posixpath? - Karl M. Davis
1
@KarlM.Davis:URL在其路径段中使用“/”。Windows上的os.path可能会使用“\”,这对于URL作为路径名分隔符是不合适的。posixpath使用“/”。 - jfs

4

使用urllib.request.Request

import urllib

req = urllib.request.Request(url, method='HEAD')
r = urllib.request.urlopen(req)
print(r.info().get_filename())

示例:

In[1]: urllib.request.urlopen(urllib.request.Request('https://httpbin.org/response-headers?content-disposition=%20attachment%3Bfilename%3D%22example.csv%22', method='HEAD')).info().get_filename()
Out[1]: 'example.csv'

1

你的问题不太清楚。你唯一拥有的是URL。 你可以从URL中提取最后一部分,或者检查HTTP响应是否包含以下内容:

content-disposition: attachment;filename="foo.bar"

服务器可以设置此标题,以指示文件名为foo.bar。这通常用于文件下载或类似操作。


0
我在谷歌上搜索了你的问题,发现之前已经在stackoverflow上有过答案。请参考以下帖子: 如何使用Python中的urllib2获取正在下载的文件名?

The filename is usually included by the server through the content-disposition header:

content-disposition: attachment; filename=foo.pdf

You have access to the headers through

result = urllib2.urlopen(...)
result.info() <- contains the headers


i>>> import urllib2
ur>>> result = urllib2.urlopen('http://zopyx.com')
>>> print result
<addinfourl at 4302289808 whose fp = <socket._fileobject object at 0x1006dd5d0>>
>>> result.info()
<httplib.HTTPMessage instance at 0x1006fbab8>
>>> result.info().headers
['Date: Mon, 04 Apr 2011 02:08:28 GMT\r\n', 'Server: Zope/(unreleased version, python 2.4.6, linux2) ZServer/1.1

Plone/3.3.4\r\n', 'Content-Length: 15321\r\n', 'Content-Type: text/html; charset=utf-8\r\n', 'Via: 1.1 www.zopyx.com\r\n', 'Cache-Control: max-age=3600\r\n', 'Expires: Mon, 04 Apr 2011 03:08:28 GMT\r\n', 'Connection: close\r\n']

See

http://docs.python.org/library/urllib2.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接