首页 > 解决方案 > 如何使用 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

标签: pythonexcelweb-scrapingpython-requestspython-requests-html

解决方案


您可以通过标题访问它。

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"'

只需filenamecontent_disposition. 您可以在此处查看 Content-Disposition Spec


推荐阅读