如何实现Telegram Bot发送20条SMS后停止迭代?
解决方案
问题根源
data.index(i)用法完全错误:index()是用来查找元素在列表中的位置,若i不是data里的元素会直接抛异常,就算是,遇到重复元素也只会返回第一个匹配的索引,根本没法实现计数终止的需求。if i >=20: break无效,大概率是循环变量i的计数逻辑有问题——比如循环里没正确累加i,或者i的起始值设置错误。
正确实现方式
方式1:用计数器控制循环
在循环外初始化计数器,每发送一条就累加,达到20就终止循环:
import telebot import requests from bs4 import BeautifulSoup bot = telebot.TeleBot("YOUR_BOT_TOKEN") @bot.message_handler(commands=['100_Слов']) def send_words(message): # 爬取单词数据 url = "你的目标网站URL" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') word_data = soup.find_all("div", class_="word-container") # 替换成实际的元素定位 count = 0 for item in word_data: if count >= 20: break # 提取英俄释义 eng_word = item.find("span", class_="english").text.strip() rus_word = item.find("span", class_="russian").text.strip() # 发送消息 bot.send_message(message.chat.id, f"{eng_word} — {rus_word}") count += 1 bot.polling()
方式2:直接切片截取前20条数据
对爬取到的单词数据列表做切片,只处理前20个元素,无需额外判断终止:
@bot.message_handler(commands=['100_Слов']) def send_words(message): url = "你的目标网站URL" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') word_data = soup.find_all("div", class_="word-container") # 只取前20条,若数据不足20条则取全部 for item in word_data[:20]: eng_word = item.find("span", class_="english").text.strip() rus_word = item.find("span", class_="russian").text.strip() bot.send_message(message.chat.id, f"{eng_word} — {rus_word}")
额外提醒
- 确保爬取逻辑能正确获取到可迭代的单词数据列表,否则循环根本不会执行。
- Telegram有发送频率限制,若发送过快可能被限制,可在每次发送后加
time.sleep(0.5)控制间隔。
内容的提问来源于stack exchange,提问作者Qupi
相关产品推荐
相关产品推荐

