爬取WhatsApp数据时如何禁用打开URL弹窗以避免代码中断?
解决Chrome通知弹窗打断Selenium运行的问题
你遇到的问题是Chrome浏览器的通知权限请求弹窗干扰了Selenium的执行,导致代码无法继续定位元素。可以通过配置ChromeOptions提前禁用通知权限来解决,同时还要修正代码里的变量定义顺序问题。
具体解决方案:
- 禁用Chrome通知权限:通过ChromeOptions添加
--disable-notifications参数,让浏览器自动拒绝通知请求,不会弹出弹窗。 - 修正变量顺序:你的代码中
n是在使用f-string之后才定义的,会触发NameError,需要把n的定义移到URL拼接之前。 - 可选扩展:如果页面还有地理位置等其他权限弹窗,可添加对应禁用参数,比如
--disable-geolocation。
修改后的完整代码:
import time 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 # 定义目标号码 n = 88888888 # 配置Chrome选项,禁用通知 chrome_options = Options() chrome_options.add_argument("--disable-notifications") # 若有其他权限弹窗,可添加对应参数,比如禁用地理位置: # chrome_options.add_argument("--disable-geolocation") # 加载驱动并应用配置 PATH = r'C:\Program Files (x86)\chromedriver' driver = webdriver.Chrome(executable_path=PATH, options=chrome_options) # 访问目标链接 driver.get(f'https://api.whatsapp.com/send/?phone=%2B234{n}&text&type=phone_number&app_absent=0') try: # 等待"Continue to Chat"元素出现 element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.LINK_TEXT, "Continue to Chat")) ) # 找到元素后可执行点击或后续爬取操作 element.click() except Exception as e: print(f"等待元素超时或出现错误: {e}") driver.quit()
代码说明:
--disable-notifications:直接禁用浏览器通知请求,从根源避免弹窗干扰Selenium执行。- 调整
n的定义顺序,确保URL拼接时变量已存在,避免报错。 - 补充异常信息打印,方便后续排查问题。
内容的提问来源于stack exchange,提问作者wesleys_theory35
相关产品推荐
相关产品推荐

