You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python Selenium结合Telegram Bot实现页面元素不存在时发送消息并完善现有脚本

Fixed Script for Element Detection & Telegram Alerts

I've gone through your code and fixed all the missing parts to meet your requirements. Here's the complete working version with detailed explanations:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
import telegram

# Initialize Chrome driver
driver = webdriver.Chrome()
driver.get("https://site123123.ma")

# Login to the site with better wait handling
try:
    # Wait for username field to load before interacting
    username_box = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="user_email"]'))
    )
    username_box.send_keys('your_email_here')
    
    password_box = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, '//*[@id="user_password"]'))
    )
    password_box.send_keys('your_password_here')
    
    submit_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="new_user"]/div[2]/div[3]/input'))
    )
    submit_button.click()
    # Give time for login to complete
    time.sleep(7)
    
    # Configure Telegram Bot
    BOT_TOKEN = '14XXXXX751:AAEY-XXXXXX-70ADVkuHawry-GO28Fk'
    CHAT_ID = '9XXXXXX13'
    bot = telegram.Bot(token=BOT_TOKEN)
    
    # Target element we're monitoring
    target_element_xpath = '//*[@id="subs-content"]/p'
    
    # Infinite loop to check element status
    while True:
        try:
            # Check if the element exists (wait up to 5 seconds for it)
            WebDriverWait(driver, 5).until(
                EC.presence_of_element_located((By.XPATH, target_element_xpath))
            )
            print("Element still exists, retrying in 60 seconds...")
            time.sleep(60)
            # Refresh page to get the latest state (optional but recommended)
            driver.refresh()
        except:
            # Element not found - send alert via Telegram
            print("Element missing! Sending alert message...")
            bot.send_message(chat_id=CHAT_ID, text='The POOL is ready You can Now take your place Fast')
            # Optional: Stop the loop after sending the alert, or remove this to keep monitoring
            break
            
finally:
    # Ensure browser closes even if an error occurs
    driver.quit()

Key Fixes & Improvements:

  • Reliable Element Checks: Replaced direct find_element calls with WebDriverWait to handle page loading delays, avoiding random NoSuchElementException errors.
  • Retry Loop: Added an infinite while loop that checks for the element every 60 seconds. If the element is present, it waits and retries; if not, it triggers the Telegram alert.
  • Telegram Integration: Fixed the send_message call to use the explicit chat_id parameter (clearer and more robust than positional arguments) and properly initialized the bot with your token.
  • Cleanup: Wrapped everything in a try-finally block to ensure the browser closes cleanly, even if the script hits an error.
  • Page Refresh: Added an optional refresh to make sure we're always checking the latest version of the page.

Quick Notes:

  • Install required packages first: pip install selenium python-telegram-bot
  • If you want the script to keep monitoring after sending the first alert, remove the break statement in the except block.
  • Adjust wait times (like the 10-second login wait or 5-second element check) based on how fast your target page loads.

内容的提问来源于stack exchange,提问作者Ayman Reifoun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 16:42:33