为什么计划和请求库在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()需要通话。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...