【问题标题】:How to get the filename of an .xls file on a website with Python (requests-html)如何使用 Python (requests-html) 在网站上获取 .xls 文件的文件名
【发布时间】:2019-01-24 08:43:17
【问题描述】:

我正在尝试从Finnish drug price agency 中抓取 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

【问题讨论】:

  • 编辑:实际上,如果您有抓取工具请求下载链接,则请求的 Content-Disposition 有一个带有该信息的 filename 字段。

标签: python excel web-scraping python-requests python-requests-html


【解决方案1】:

您可以通过标题访问它。

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

只需从content_disposition 解析filename。您可以查看Content-Disposition Spec here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2011-03-27
    • 2019-08-16
    相关资源
    最近更新 更多