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

如何使用Selenium Python点击Telegram弹窗的Отмена按钮

解决Telegram网页端弹窗无法用Selenium alert方法点击的问题

你遇到的弹窗是Telegram网页端的自定义模态框,不属于浏览器原生的alert弹窗,所以driver.switch_to.alert方法完全无效,必须用普通的页面元素定位方式来操作。

解决方案步骤:

  • 抛弃time.sleep,改用显式等待确保弹窗元素加载完成(比固定等待更稳定)
  • 通过元素定位方式找到“Отмена”按钮并点击

修改后的完整代码:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import undetected_chromedriver as uc

# 添加额外配置减少弹窗干扰
options = webdriver.ChromeOptions()
options.add_argument("--disable-notifications")
options.add_argument("--disable-popup-blocking")

driver = uc.Chrome(options=options)
driver.get('https://t.me/rian_ru')

try:
    # 最多等待10秒,直到取消按钮可点击
    cancel_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//button[text()='Отмена']"))
    )
    cancel_button.click()
    print("已成功点击取消按钮")
except Exception as e:
    print(f"操作失败: {str(e)}")

# 后续操作...
# driver.quit()

定位方式备选:

如果上述xpath定位失败,可以尝试用文本包含的方式(兼容按钮文本带空格的情况):

By.XPATH, "//button[contains(text(), 'Отмена')]"

或者通过按钮的class属性定位(需先查看该按钮的class,比如Telegram弹窗的取消按钮可能带有btn-secondary类):

By.CLASS_NAME, "btn-secondary"

内容的提问来源于stack exchange,提问作者Вишня

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:32:44