Answer the question
In order to leave comments, you need to log in
Telegram bot in python: error variable is not defined?
Recently I started to deal with bots on Python. Found an example of how to parse the weather. I added the code to myself, but the error tortured me.
My code:
import telebot
import requests
from bs4 import BeautifulSoup as BS
r = requests.get('https://sinoptik.ua/погода-харьков')
html = BS(r.content, 'html.parser')
bot = telebot.TeleBot('1113481836:AAGB_KMA0glwKctU2sKiH6bLS1zTyYYavlo')
keyboard1 = telebot.types.ReplyKeyboardMarkup()
keyboard1.row(' Rozklad', '⚙️ Кнопка4','Погода')
keyboard1.row(' Наш сайт', ' Зворотній зв`язок')
for el in html.select('#content'):
t_min = el.select('.temperature .min')[0].text
t_max = el.select('.temperature .max')[0].text
text = el.select('.wDescription .description')[0].text
@bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id, 'Привіт, '+ message.from_user.username)
@bot.message_handler(content_types=['text'])
def send_text(message):
# global t_min
if message.text == ' Rozklad':
bot.send_message(message.chat.id, 'Обери курс:', reply_markup=kurs)
# if message.text == 'Погода':
# global tmin
# bot.send_message(message.chat.id, tmin, reply_markup=kurs)
if message.text == 'Погода':
bot.send_message(message.chat.id, "Привет, погода на сегодня \n" +
t_min + ', ' + t_max + '\n' + text)
if __name__ == '__main__':
bot.polling(none_stop=True)
Answer the question
In order to leave comments, you need to log in
Understand the basics of the language first. Read some textbook.
The error says that there is no t_min variable. It only surrenders within the cycle. Those. most likely html.select(...) returns an empty list (or its own empty iterable object).
You can try to declare variables t_min, t_max, text (for example t_min = "" ) before the loop, and the error should disappear
Study the page you are parsing first.
The elements you are looking for have only one class, and you are looking for them in two classes.
And the element with the class "wDescription description"
does not exist at all.
You need to get the element of the class first "temperature"
, and then pull out the elements with the temperature from it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question