skip to Main Content

I’m making a telegram bot that will send SMS through a parser and I need to loop until about 20 SMS are sent.
I am using the telebot library to create a bot and for the parser I have requests and BeautifulSoup.

import telebot
import requests
from bs4 import BeautifulSoup
from telebot import types

bot = telebot.TeleBot('my token')

@bot.message_handler(commands=['start'])
def start(message):
    mess = f'Привет, сегодня у меня для тебя 100 Анг слов! Удачи <b>{message.from_user.first_name}</b>'
    bot.send_message(message.chat.id, mess, parse_mode='html')

@bot.message_handler(commands=['words'])
def website(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
    word = types.KeyboardButton('100 Слов')
    markup.add(word)#создание самой кнопки.
    bot.send_message(message.chat.id, 'Подевиться слова', reply_markup=markup)

@bot.message_handler(content_types=['text'])
def get_user_commands(message):
    if message.text == '100 Слов':
        url = 'https://www.kreekly.com/lists/100-samyh-populyarnyh-angliyskih-slov/'
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'lxml')
        data = soup.find_all("div", class_="dict-word")
        for i in data:
            ENG = i.find("span", class_="eng").text
            rU = i.find("span", class_="rus").text
            bot.send_message(message.chat.id, ENG, parse_mode='html')
            bot.send_message(message.chat.id, rU, parse_mode='html')

bot.polling(none_stop=True)

I tried to do it this way:

if i >= 20:
   break

but this does not work. I also tried to do it like this:

if data.index(i) >= 20
   break

2

Answers


  1. Don’t bother with the stopping the loop or slicing the array, tell bs4 to limit the result:

    data = soup.find_all("div", class_="dict-word", limit=20)
    
    Login or Signup to reply.
  2. you can try

    for indx,i in enumerate(data):
        if index == 19: # including zero, 20th will be the 19th.
            break
        -code here-
    

    enumerate function keeps track of current step, so at first iteration indx = 0 , second indx=1 and so on.

    for indx,i in enumerate(data):
            if index < 20: # apply the code if it's under the 20th itereation.
                -code here-
    

    I suggest the upper solution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search