使用python下载CSV文件

时间:2019-09-16 11:48:03

标签: python-3.x

我正尝试使用以下代码使用Python从Yahoo Finance下载历史股价:

var person = new Person("Jesse de Wit", new DateTime(1988, 5, 27));
var serializer = new DataContractSerializer(typeof(Person));
using (var stream = new MemoryStream())
{
    serializer.WriteObject(stream, person);
}

但是,我得到了如下所述的回溯:

import urllib.request
import ssl
import os

url = 'https://query1.finance.yahoo.com/v7/finance/download/%5ENSEI?period1=1537097203&period2=1568633203&interval=1d&events=history&crumb=0PVssBOEZBk'

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

connection = urllib.request.urlopen(url,context = ctx)
data = connection.read()

with urllib.request.urlopen(url) as testfile, open('data.csv', 'w') as f:
    f.write(testfile.read().decode())

我认为这与以下事实有关:这是因为HTTPS,默认情况下,Python没有足够的证书可放入其中。

该网页的即时信息位于Yahoo Finance NSEI historical prices上,位于“下载数据”选项卡上,您可以单击该位置通过CSV文件自动下载数据。

请帮助您纠正代码?

1 个答案:

答案 0 :(得分:0)

yahoo api希望浏览器中的cookie进行身份验证。我已经从浏览器中复制了cookie,并通过python请求传递了它们

import requests
import csv


url = "https://query1.finance.yahoo.com/v7/finance/download/%5ENSEI?period1=1537099135&period2=1568635135&interval=1d&events=history&crumb=MMDwV5mvf2J"


cookies = {
            "APID":"UP26c2bef4-bc0b-11e9-936a-066776ea83e8",
            "APIDTS":"1568635136",
            "B":"d10v5dhekvhhg&b=3&s=m6",
            "GUC":"AQEBAQFda2VeMUIeqgS6&s=AQAAAICdZvpJ&g=XWoXdg",
            "PRF":"t%3D%255ENSEI",
            "cmp":"t=1568635133&j=0",
            "thamba":"2"
    }
with requests.Session() as s:
    download = s.get(url,cookies=cookies)

    decoded_content = download.content.decode('utf-8')

    cr = csv.reader(decoded_content.splitlines(), delimiter=',')
    my_list = list(cr)
    for row in my_list:
        print(row)