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

如何用Python版Selenium处理Chrome中的WhatsApp Web弹窗

解决Selenium操作wa.me时的外部协议弹窗问题

你遇到的这个弹窗不是网页原生的JS Alert,而是Chrome浏览器的外部协议请求确认框(用来确认是否打开WhatsApp相关应用/网页),所以用switch_to.alert肯定找不到,会报NoAlertPresentException。手动操作没弹窗是因为浏览器可能已经记住了你的选择,自动跳过了确认步骤。

直接给可行方案:

方案:配置Chrome跳过外部协议提示

给ChromeDriver添加启动参数,让浏览器自动允许打开外部协议链接,直接跳过确认弹窗。

修改后的完整代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

# 配置Chrome参数,跳过外部协议提示
chrome_options = Options()
chrome_options.add_argument("--no-default-browser-check")
chrome_options.add_argument("--disable-external-protocol-dialog")

# 注意路径用原始字符串避免转义问题
PATH = r"C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(executable_path=PATH, options=chrome_options)

num = "xxxxxxxxxxxxxxxxxxxxx" # 替换为目标手机号
driver.get("https://wa.me/" + num)

# 用显式等待替代隐式等待,更可靠
wait = WebDriverWait(driver, 10)

# 等待"Share on WhatsApp"按钮加载并点击
share_btn = wait.until(EC.element_to_be_clickable((By.ID, "action-button")))
share_btn.click()

# 等待跳转WhatsApp Web的链接加载并点击
web_link = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="fallback_block"]/div/div/h4[2]/a')))
web_link.click()

关键说明

  1. 参数作用:
    • --disable-external-protocol-dialog:直接禁用外部协议的确认弹窗,自动允许打开
    • --no-default-browser-check:避免浏览器检查默认应用的提示,减少干扰
  2. 移除无效代码:删掉所有driver.switch_to.alert.accept()和driver.switch_to_alert().accept(),这些操作对浏览器级弹窗完全无效
  3. 显式等待:用WebDriverWait代替implicitly_wait,可以精准等待元素可点击,避免因加载慢导致的元素找不到问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:00:55