如何使用Python请求获取pdf文件名? [英] How to get pdf filename with Python requests?

查看:822
本文介绍了如何使用Python请求获取pdf文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python requests lib 从网络上获取PDF文件.这可以正常工作,但我现在也想要原始文件名.如果我在Firefox中转到PDF文件并单击download,则它已经定义了文件名来保存pdf.如何获取该文件名?

I'm using the Python requests lib to get a PDF file from the web. This works fine, but I now also want the original filename. If I go to a PDF file in Firefox and click download it already has a filename defined to save the pdf. How do I get this filename?

例如:

import requests
r = requests.get('http://www.researchgate.net/profile/M_Gotic/publication/260197848_Mater_Sci_Eng_B47_%281997%29_33/links/0c9605301e48beda0f000000.pdf')
print r.headers['content-type']  # prints 'application/pdf'

我检查了r.headers中是否有有趣的内容,但是其中没有文件名.我实际上希望的是类似r.filename ..

I checked the r.headers for anything interesting, but there's no filename in there. I was actually hoping for something like r.filename..

有人知道我如何通过请求库获取下载的PDF文件的文件名吗?

Does anybody know how I can get the filename of a downloaded PDF file with requests library?

推荐答案

在http标头content-disposition中指定.因此,要提取名称,您将执行以下操作:

It is specified in an http header content-disposition. So to extract the name you would do:

import re
d = r.headers['content-disposition']
fname = re.findall("filename=(.+)", d)[0]

通过正则表达式(re模块)从字符串中提取的名称.

Name extracted from the string via regular expression (re module).

这篇关于如何使用Python请求获取pdf文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆