为什么计划和请求库在Python中不适用于该类?

问题描述

我是一个初学者。我有一个班级,我想每天在某个小时一次从网站上获取一些数据(这里是每秒,因为我正在测试)。我想使用时间表模块,但我不知道是什么问题。我使用Pycharm,程序仅运行而没有输出

import requests
import time
import schedule

class Bot:
    def __init__(self):
        self.url = 'https://www.website.com'
        self.params = {
        ...
        }
        self.headers = {
        ...
        }

        self.orders = []

    def fetchCurrenciesData(self):
        r = requests.get(url=self.url,headers=self.headers,params=self.params).json()
        return r['data']


schedule.every(5).seconds.do(Bot)

while True:
    schedule.run_pending()
    time.sleep(1)

我也尝试这样做:

impactBot = Bot()

schedule.every(5).seconds.do(impactBot())

while True:
    schedule.run_pending()
    time.sleep(1)

但是在这里,我收到一个错误消息,他们说“ Bot对象不可调用”。我该怎么办?

解决方法

您需要为初始化对象调用类,然后再调用对象类的方法。 要解决该问题,请遵循我的示例:

ClassObj = Bot()
# Call method fetchCurrenciesData
ClassObj.fetchCurrenciesData()

# or 
# Singal line
Bot().fetchCurrenciesData()

下面是您的代码示例。

import requests
import time
import schedule

class Bot:
    def __init__(self):
        self.url = 'https://www.website.com'
        self.params = {
        ...
        }
        self.headers = {
        ...
        }

        self.orders = []

    def fetchCurrenciesData(self):
        r = requests.get(url=self.url,headers=self.headers,params=self.params).json()
        return r['data']


schedule.every(5).seconds.do(Bot().fetchCurrenciesData())

while True:
    schedule.run_pending()
    time.sleep(1)
,

尝试一下:

impactBot = Bot()

schedule.every(5).seconds.do(impactBot.fetchCurrenciesData)

while True:
    schedule.run_pending()
    time.sleep(1)

schedule....do()需要通话。