通过Python在网页内下载CSV

2024-06-17 11:51:33 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法使用Python下载下面链接中名为“EXPE-Key-rations.CSV”的CSV文件

http://financials.morningstar.com/ratios/r.html?t=EXPE&region=usa&culture=en-US

如果没有Python,可以通过单击“导出”按钮轻松下载,但我不懂Javascript,也不知道如何通过追踪JS代码生成Python中的真正下载路径。我试图按照this post中的步骤进行操作,但我无法根据我的问题进行调整。感谢您的帮助


Tags: 文件csvkeycomhttp链接htmlregion
2条回答

不需要selenium,缺少的是Referer标头。javascript函数只是将order方法附加到http://financials.morningstar.com/finan/ajax/exportKR2CSV.html?&callback=?&t=XNAS:EXPE&region=usa&culture=en-US&cur=&order=,默认方法是asc

import requests

headers = {
'Referer': 'http://financials.morningstar.com/ratios/r.html?t=EXPE&region=usa&culture=en-US',
}

r = requests.get("http://financials.morningstar.com/finan/ajax/exportKR2CSV.html?&callback=?&t=XNAS:EXPE&region=usa&culture=en-US&cur=&order=asc", headers=headers)

csv = r.content

with open("EXPE Key Ratios.csv", "wb") as file:
    file.write(csv)

好的,我一直在做这个,最近的一次是把它放到你的下载文件夹中,我不知道这个网站是如何与浏览器交互来调用这样的直接下载的。如果有人对这一切的后端更了解,能够解释它是如何工作的,我将不胜感激

无论如何,以下是我将其放入下载文件夹的代码:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

#Get a driver
driver = webdriver.Edge()

#Navigate to the page
driver.get('http://financials.morningstar.com/ratios/r.html?t=EXPE&region=usa&culture=en-US')

#This is the javascript function that is invoked.
driver.execute_script("exportKeyStat2CSV()")

#Close the browser
driver.quit()

这将把csv放在下载文件夹中(无论是在什么地方)

要安装webdriver gohere,请下载它并将其与脚本一起放入目录中。您必须pip安装selenium

相关问题 更多 >