有没有可能获取文件名
e.g. xyz.com/blafoo/showall.html
如果您使用urllib或httplib?
这样我就可以将文件保存在服务器上的文件名下了吗?
如果您访问类似于的网站
xyz.com/blafoo/
您无法看到文件名。
谢谢
从响应的 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
模块,而是应该使用posixpath
模块。如果您不能理解为什么,请问我,我会详细说明。请注意,这里使用os.path
是错误的。 - jfs使用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'
你的问题不太清楚。你唯一拥有的是URL。 你可以从URL中提取最后一部分,或者检查HTTP响应是否包含以下内容:
content-disposition: attachment;filename="foo.bar"
服务器可以设置此标题,以指示文件名为foo.bar。这通常用于文件下载或类似操作。
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