python httplib/urllib get filename

HappyHacking picture HappyHacking · Aug 2, 2012 · Viewed 12.1k times · Source

is there a possibillity to get the filename

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

if you work with urllib or httplib?

so that i can save the file under the filename on the server?

if you go to sites like

xyz.com/blafoo/ 

you cant see the filename.

Thank you

Answer

jfs picture jfs · Aug 2, 2012

To get filename from response http headers:

import cgi

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

To get filename from the URL:

import posixpath
import urlparse 

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