我正在使用Mechanize下载文件,在响应头中有一个字符串:
Content-Disposition: attachment; filename=myfilename.txt
是否有快速标准的方法来获取该文件名值? 我现在想到的是:
filename = f[1]['Content-Disposition'].split('; ')[1].replace('filename=', '')
但它看起来像是一个快速的肮脏解决方案。
答案 0 :(得分:31)
首先使用mechanize获取标头的值,然后使用内置的cgi模块解析标头。
演示:
>>> import mechanize
>>> browser = mechanize.Browser()
>>> response = browser.open('http://example.com/your/url')
>>> info = response.info()
>>> header = info.getheader('Content-Disposition')
>>> header
'attachment; filename=myfilename.txt'
然后可以解析标头值:
>>> import cgi
>>> value, params = cgi.parse_header(header)
>>> value
'attachment'
>>> params
{'filename': 'myfilename.txt'}
params
是一个简单的字典,因此您需要params['filename']
。
文件名是否用引号括起来并不重要。
答案 1 :(得分:5)
这些正则表达式基于RFC 6266的语法,但经过修改以接受没有处置类型的标题,例如: Content-Disposition:filename = example.html
即。 [disposition-type“;” ] disposition-parm(“;”disposition-parm)* / disposition-type
它将使用和不使用引号处理文件名参数,并从引号中的值中取消引用引用的对,例如filename =“foo \”bar“ - > foo”bar
它将处理filename *扩展参数,并且更喜欢文件名*扩展参数而不管它们在标题中出现的顺序
它剥离文件夹名称信息,例如/ etc / passwd - > passwd,默认为URL路径中的basename,缺少filename参数(或标题,或者如果参数值为空字符串)
token和qdtext正则表达式基于RFC 2616的语法,mimeCharset和valueChars正则表达式基于RFC 5987的语法,语言正则表达式基于RFC 5646的语法
import re, urllib
from os import path
from urlparse import urlparse
# content-disposition = "Content-Disposition" ":"
# disposition-type *( ";" disposition-parm )
# disposition-type = "inline" | "attachment" | disp-ext-type
# ; case-insensitive
# disp-ext-type = token
# disposition-parm = filename-parm | disp-ext-parm
# filename-parm = "filename" "=" value
# | "filename*" "=" ext-value
# disp-ext-parm = token "=" value
# | ext-token "=" ext-value
# ext-token = <the characters in token, followed by "*">
token = '[-!#-\'*+.\dA-Z^-z|~]+'
qdtext='[]-~\t !#-[]'
mimeCharset='[-!#-&+\dA-Z^-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*)?(?:{dispositionParm})(?:\s*;\s*(?:{dispositionParm}))*|{token}'.format(**locals()), result.headers['Content-Disposition'])
except KeyError:
name = path.basename(urllib.unquote(urlparse(url).path))
else:
if not m:
name = path.basename(urllib.unquote(urlparse(url).path))
# Many user agent implementations predating this specification do not
# understand the "filename*" parameter. Therefore, when both "filename"
# and "filename*" are present in a single header field value, recipients
# SHOULD pick "filename*" and ignore "filename"
elif m.group(8) is not None:
name = urllib.unquote(m.group(8)).decode(m.group(7))
elif m.group(4) is not None:
name = urllib.unquote(m.group(4)).decode(m.group(3))
elif m.group(6) is not None:
name = re.sub('\\\\(.)', '\1', m.group(6))
elif m.group(5) is not None:
name = m.group(5)
elif m.group(2) is not None:
name = re.sub('\\\\(.)', '\1', m.group(2))
else:
name = m.group(1)
# Recipients MUST NOT be able to write into any location other than one to
# which they are specifically entitled
if name:
name = path.basename(name)
else:
name = path.basename(urllib.unquote(urlparse(url).path))
答案 2 :(得分:-1)
我会尝试类似的事情:
import re
filename = re.findall("filename=(\S+)", f[1]['Content-Disposition'])
它处理文件名上的引号和URL转义。