如何在Python中使用Selenium阻止弹出窗口?

0s7z1bwu  于 2023-06-06  发布在  Python
关注(0)|答案(3)|浏览(442)

弹出窗口正在搞乱一个我试图使用selenium/python创建的web scraper。目标是从网页的每个子页面中提取文本。但是,在随机情况下会出现此弹出窗口:

我试图从webdriver的选项中消除弹出窗口,但它不起作用。下面是chrome示例的代码:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

options = Options()
options.add_argument('--headless')
options.add_experimental_option('detach', True)
options.add_argument("--disable-popup-blocking")
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

有什么建议吗?

xxhby3vn

xxhby3vn1#

如果弹出窗口出现在特定时间点,您可以单击X元素关闭弹出窗口。但是,如果弹出窗口是随机弹出的,则很难使用selenium-webdriver进行处理。
一个更简单和理想的方法是要求开发人员/devops团队在测试环境中禁用弹出窗口,以便进行自动化测试。

nuypyhwy

nuypyhwy2#

  • 这不是一个弹出窗口,它更像是一个“吐司”(这就是为什么选项options.add_argument("--disable-popup-blocking")不起作用)。
  • 您可以关闭它,甚至更好地删除它,但服务器可能会呈现一个新的。
  • 您可以尝试删除元素(发送一些javascript),希望服务器不会呈现新的元素。如果服务器呈现一个新的,您可以尝试再次删除它。
  • 要定位元素,您应该查找上面的几行(父元素)。

尝试使用其中一个:

按Id编写脚本

js = """
element = document.getElementById("your id");
element.remove();
"""

按类编写脚本

js = """
element = document.getElementsByClassName("your classes");
element[0].remove()
"""

然后执行脚本

执行脚本

driver.execute_script(js)
csga3l58

csga3l583#

要使用Selenium和Python处理弹出窗口,可以使用WebDriverWait类沿着Selenium提供的预期条件。通过等待弹出窗口出现并处理它,您可以继续执行自动化脚本。

# Wait for the pop-up window to appear
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
    
    # Switch to the pop-up window
    windows = driver.window_handles
    driver.switch_to.window(windows[1])

    # Close the pop-up window
    driver.close()
    
    # Switch back to the main window (if needed)
    driver.switch_to.window(windows[0])

相关问题