首页 > 解决方案 > 在 selenium python 中处理弹出窗口

问题描述

我目前正在开展一个项目,我正在通过 url 自动化 whatsapp 消息。像这样https://wa.me/number_here

每当我正常执行此操作时,一切都很好,但是当我尝试自动执行此操作时,会出现一个whatsapp弹出框并阻止所有内容,我的意思是所有内容,没有右键单击没有开发人员选项,这就是为什么我无法获得按钮的x路径的原因那个弹出窗口。我试过(driver.shift_to,alert.close)但它说没有这样的警报。我试图通过 contains(text) 方法找到按钮,但也没有用。这是我的代码。

chrome_options = Options()
chrome_options.add_argument('--user-data-dir = user-data') 
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])  
chrome_options.add_argument('--disable-notifications')      
chrome_options.add_argument('--disable-popup-blocking')
chrome_options.add_experimental_option('useAutomationExtension', False)

driver = webdriver.Chrome(options=chrome_options, executable_path= driver_path)
wait = WebDriverWait(driver, 60)
contact = f'https://wa.me/{number}'        

    driver.get(contact)      
    time.sleep(3)

    alert = wait.until(EC.alert_is_present())
    alert.accept() 

在此处输入图像描述

请帮助我如何绕过此弹出窗口。谢谢

标签: pythonseleniumgoogle-chrome

解决方案


我认为,此链接可能对您有所帮助: https ://stackoverflow.com/a/19019311/12000849

我所做的是在我希望看到警报的点之前使用 WebDriverWait 设置条件延迟,然后切换到它,如下所示:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("url")
browser.find_element_by_id("add_button").click()

try:
    WebDriverWait(browser, 3).until(EC.alert_is_present(),
                                   'Timed out waiting for PA creation ' +
                                   'confirmation popup to appear.')

    alert = browser.switch_to.alert
    alert.accept()
    print("alert accepted")
except TimeoutException:
    print("no alert")

推荐阅读