python - 如何使用 Python (requests-html) 在网站上获取 .xls 文件的文件名
问题描述
我正在尝试从芬兰药品价格机构抓取 excel 文件
我正在使用 requests-html 来查找指向 excel 文件的链接:
from requests_html import HTMLSession
import urllib.request
url = 'http://www.hila.fi/fi/hakeminen_ja_ilmoitukset/viitehintajarjestelma/ryhmat_ja_hinnat/viitehintapaatokset2009'
session = HTMLSession()
r = session.get(url)
sel = 'a[href*=".xls"]'
reference_datas = r.html.find(sel)
for reference_data in reference_datas:
url = reference_data.absolute_links.pop()
response = urllib.request.urlopen(url)
with open('test.xls', 'wb') as f:
f.write(response.read())
这适用于 excel 文件的内容,但所选元素没有关于文件名称的信息。文件名包含文件中价格适用时期的信息。例如链接http://www.hila.fi/c/document_library/get_file?folderId=792534&name=DLFE-4531.xls
获取文件Viitehintaluettelo Q4_2009_paivitetty.xls
。
如何将此文件名作为字符串获取,以便从中提取时间信息Q4_2009
?
解决方案
您可以通过标题访问它。
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('http://www.hila.fi/c/document_library/get_file?folderId=792534&name=DLFE-4531.xls')
content_disposition = r.headers.get('Content-Disposition')
print(content_disposition)
# 'attachment; filename="Viitehintaluettelo Q4_2009_paivitetty.xls"'
只需filename
从content_disposition
. 您可以在此处查看 Content-Disposition Spec。
推荐阅读
- javascript - JavaScript - 获取嵌套属性的父对象
- javascript - 有没有办法创建一个命名的立即调用的箭头函数表达式?
- ios - WKWebKit 错误 - 连接中断 [XPC] 处理连接错误:连接中断
- sqlite - SQLite:使用双射表替换结果值
- node.js - 使用 IIS 部署 NodeJS 应用程序
- java - 从 Spring 上下文到 Spring 注解
- node.js - 使用 node.js 创建 Strappoll.me 民意调查
- java - 从 WSDL 创建 Web 服务的 .jar
- python - Python - 'for'循环中的错误以实现字典的最大值
- javascript - 我有一个最大长度为 2 的输入字段,如果我输入 0 - 9 个值,它应该给出 01,02 等,对于 10 以上,它应该给出相同的值