Почему не обновляются данные парсинга после нажатия кнопки в боте телеграмм
написал парсер для получения данных о погоде, вычленил нужные данные, подключил это все дело к боту. При первом запуске данные передаются, но при повторных нажатиях кнопки "Узнать погоду", данные остаются старые, то есть функция как будто не выполняется. Что я сделал неверно и как это поправить?
import telebot
from bs4 import BeautifulSoup
import requests
from telebot import types
введите сюда код
url = 'https://pogoda.mail.ru/prognoz/moskva/'
response = requests.get(url)
def weather(url):
bs = BeautifulSoup(response.text, "lxml")
temp = bs.find('div', 'information__content__temperature').text.strip()
city = bs.find('h1', 'information__header__left__place__city').text.strip()
date = bs.find('div', 'information__header__left__date').text.strip()
react = bs.find('div', 'information__content__additional__item').text.strip()
s = bs.find('div', 'information__content__additional information__content__additional_first').text.strip()
result = f'{city}: {temp}, {react}, {s}, {date}'
return result
res = weather(url)
bot = telebot.TeleBot('5602472525:AAGk8vUDt80xAMzWiXDdPuGgGD111sf_q5cjCuo')
@bot.message_handler(commands=["start"])
def start(message, res=False):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
btn1 = types.KeyboardButton("Узнать погоду")
markup.add(btn1)
bot.send_message(message.chat.id, text='Жми кнопку'.format(message.from_user), reply_markup=markup)
@bot.message_handler(content_types=['text'])
def func(message):
if(message.text == "Узнать погоду"):
bot.send_message(message.chat.id, res)
bot.polling()
Ответы (1 шт):
Автор решения: Johan
→ Ссылка
У вас запрос данных находиться за пределами функции парсинга данных о погоде. Перенесите запрос в функцию, а также параметр url. Примерно это будет выглядеть так:
def weather():
response = requests.get('https://pogoda.mail.ru/prognoz/moskva/')
bs = BeautifulSoup(response.text, "lxml")
temp = bs.find('div', 'information__content__temperature').text.strip()
city = bs.find('h1', 'information__header__left__place__city').text.strip()
date = bs.find('div', 'information__header__left__date').text.strip()
react = bs.find('div', 'information__content__additional__item').text.strip(
s = bs.find('div', 'information__content__additional information__content__additional_first').text.strip(
result = f'{city}: {temp}, {react}, {s}, {date}'
return result
Если вы запрос погоды будете делать в другом городе, тогда url надо будет делать не постоянным, а передавать в функцию из бота. То есть, вернуть url:
def weather(url):
response = requests.get(url)