如何使用 Python (requests-html) 获取网站上 .xls 文件的文件名
How to get the filename of an .xls file on a website with Python (requests-html)
我正在尝试从 Finnish drug price agency
中抓取 excel 文件
我正在使用请求-html 查找 excel 文件的 link:
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 文件的内容,但所选元素没有关于文件名的信息。文件名包含有关文件中价格适用期间的信息。例如 link http://www.hila.fi/c/document_library/get_file?folderId=792534&name=DLFE-4531.xls
获取文件 Viitehintaluettelo Q4_2009_paivitetty.xls
.
如何获取字符串形式的文件名,以便从中提取时间信息Q4_2009
?
您可以通过headers访问它。
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 .
我正在尝试从 Finnish drug price agency
中抓取 excel 文件我正在使用请求-html 查找 excel 文件的 link:
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 文件的内容,但所选元素没有关于文件名的信息。文件名包含有关文件中价格适用期间的信息。例如 link http://www.hila.fi/c/document_library/get_file?folderId=792534&name=DLFE-4531.xls
获取文件 Viitehintaluettelo Q4_2009_paivitetty.xls
.
如何获取字符串形式的文件名,以便从中提取时间信息Q4_2009
?
您可以通过headers访问它。
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 .