簡體   English   中英

Python 從 URL 獲取數據並在 Google 表格中寫入不適用於 heroku?

[英]Python get data from URL and write in Google sheet not working on heroku?

這是我從 URL 獲取數據並寫入谷歌表的主要程序 -

import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

import requests
import datetime
import pandas as pd

def writedata():
    # Connect to Google Sheet
    credentials = ServiceAccountCredentials.from_json_keyfile_name('creds.json',scope)
    client = gspread.authorize(credentials)
    sheet = client.open("Min15Scan").sheet1
    symlist = sheet.col_values(1)

    i = 2
    while i <= len(symlist):
        symbolfromexcel = symlist[i-1] + "EQN"
        # URL of NSEIndia chart data
        headers = {'User-Agent': 'Mozilla/5.0'}
        try:
            url = 'https://www.nseindia.com/api/chart-databyindex?index=' + symbolfromexcel
            r = requests.get(url, headers=headers)
            data = r.json()
            prices = data['grapthData']

            # Create Empty Dataframe/List to add data
            rawdata = []

            # Loop to get data & write into list (rawdata) as list of list
            for item in prices:
                dt = datetime.datetime.utcfromtimestamp(item[0] / 1000)
                value = item[1]
                rawdata.append([dt.strftime('%H-%M'), value])

            # Create dataframe
            data_df = pd.DataFrame(rawdata, columns=["Time", "ltp"])

            min15 = data_df.loc[data_df["Time"] <= "09-30"]
            min15 = min15["ltp"]
            min15max = min15.max()
            min15min = min15.min()

            total = data_df["ltp"]
            totalmax = total.max()
            totalmin = total.min()

            # Write data on raw sheet.update('B1', 'text')
            sheet.update('B' + str(i) + ':E' + str(i), [[min15max, min15min, totalmax, totalmin]])
        except:
            sheet.update('B' + str(i) + ':E' + str(i), [[0, 0, 0, 0]])
            pass

        i = i + 1

時鍾文件-

from apscheduler.schedulers.blocking import BlockingScheduler
from GoogleSheetAPI import writedata
sched = BlockingScheduler()

sched.add_job(writedata, 'interval', minutes=5)
sched.start()

如果我在我的 PC 上運行它,它工作正常,但它的寫作除了部分 (sheet.update('B' + str(i) + ':E' + str(i), [[0, 0, 0, 0]] )) 每次,我都無法理解什么是錯誤。

您的代碼遇到異常並執行“ except: ”語句。 所以它執行sheet.update('B' + str(i) + ':E' + str(i), [[0, 0, 0, 0]])然后pass如果你不這樣做,這不是很有用'不知道你會得到什么例外。

嘗試打印異常,例如如下:

except Exception as e:
    print(e)

以了解有關錯誤的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM