【问题标题】:Download a CSV inside a webpage through Python通过 Python 在网页中下载 CSV
【发布时间】:2020-11-29 02:14:06
【问题描述】:

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

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

如果没有 Python,可以通过单击“导出”按钮轻松下载,但我没有 Javascript 知识,也不知道如何通过追踪 JS 代码在 Python 中生成真正的下载路径。我尝试按照this post 中的步骤进行操作,但我无法针对我的问题进行定制。任何帮助表示赞赏。

【问题讨论】:

  • 看看 selenium,它可以让你通过 python 驱动一个网络浏览器。

标签: javascript python csv


【解决方案1】:

不需要硒,缺少的是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)

【讨论】:

    【解决方案2】:

    好的,所以我一直在处理这个问题,我最接近的是将它放入您的下载文件夹——我不知道这个网站是如何与浏览器交互来调用像这样的直接下载的。如果对所有这些后端有更多了解的人可以解释它是如何工作的,我将不胜感激。

    无论如何,这是我将其下载到下载文件夹的代码:

    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,请转到 here,下载它并将其放入脚本所在的目录中。你必须 pip install selenium。

    【讨论】:

      猜你喜欢
      • 2019-01-15
      • 2012-02-27
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2010-10-14
      相关资源
      最近更新 更多