来自同一网址的多个导入请求

时间:2019-02-15 11:18:53

标签: python stock

我想使用以下代码下载股票的流通量数据,然后将其写入json文件。

import requests
import json

filename='float.json'

url = "https://api.iextrading.com/1.0/stock/aapl/stats"   
response = requests.get(url).json()
data = (response['symbol'], response['float'])

with open(filename, 'a+') as outfile:
    json.dump(data, outfile, indent=4)

现在,我想下载多只股票的数据,因此在网址中显示为“ aapl”的地方,我想要多股股票,例如“ tsla”,“ goog”等。

有人可以向我解释如何实现这一目标吗?

亲切问候

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法吗?

import json
import requests
stk_list = ['aapl', 'tsla', 'goog']
for stk_name in stk_list:
    try:
        url = "https://api.iextrading.com/1.0/stock/{}/stats".format(stk_name)
        response = requests.get(url).json()
        data = (response['symbol'], response['float'])
        filename = 'float_{}.json'.format(stk_name)

        with open(filename, 'a+') as outfile:
            json.dump(data, outfile, indent=4)
    except:
        pass

答案 1 :(得分:0)

您可以尝试:

import json

import requests


stocks = ['appl', 'goog']

base_url = 'https://api.iextrading.com/1.0/stock/{}/stats'

filename='float.json'

for stock in stocks:

    try:
        response = requests.get(base_url.format(stock))
    except:
        continue
    if response.status_code == 200:
        response_json = response.json()
        data = (response_json['symbol'], response_json['float'])

        with open(filename, 'a+') as outfile:
            json.dump(data, outfile, indent=4)