我正在尝试使网站上的流程自动化。当不清楚弹出窗口 window 何时出现时,如何使用 selenium 关闭弹出窗口 window?

I'm trying to automate a process on a website. How do I close a pop up window with selenium, when it is not clear when the popup window will appear?

我正在尝试用 python 中的 selenium 关闭弹出窗口 window,这不允许我的代码进一步执行。但我无法那样做。有一个弹出窗口 window 问我是否要注册,但它总是在不一致的时间弹出。有没有一种方法可以检查弹出窗口 window 是否处于活动状态?

到目前为止我的代码:

    import selenium
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    import time 

    PATH = "C:\Program Files (x86)\chromedriver.exe";
    driver = webdriver.Chrome(PATH);



    driver.get("https://www.investing.com/news/")
    time.sleep(3)
    accept_cookies = driver.find_element_by_xpath('//*[@id="onetrust-accept-btn-handler"]');
    accept_cookies.click();
    

你可以用我马上想到的 2 个快速方法来完成。

1:

  • 你会经常用到这个
from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

然后当你想获取一个需要时间加载的元素并且你想用它做一些动作时,你可以用 WebDriverWait 实现它:

wait = WebDriverWait(driver, 10)
try:
    accept_cookies = wait.until(EC.presence_of_element_located((By.XPATH, "'//* 
    [@id=\"onetrust-accept-btn-handler\"]'")))
catch:
    # probably you have a bad locator and the element doesn't exist or it needs more than 10 sec to load.
else:
    # logic here is processed after successfully obtaining the pop up
    accept_cookies.click()
  • 我会推荐使用 ActionChains
from selenium.webdriver.common.action_chains import ActionChains

然后在获得弹出元素后,点击如下:

actions = ActionChains(driver)
actions.move_to_element(accept_cookies).click().perform()

这相当于将鼠标指针移动到弹出关闭按钮的中间并单击它

所以你的问题是你不想显示注册弹出窗口。

我刚刚查看了该站点的脚本,我发现了一个非常好的解决方法:将用户代理设置为 gene。如果用户代理匹配某些移动浏览器,显示弹出窗口的脚本将被禁用。

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=gene")
driver = webdriver.Chrome(options=opts)

# Adds the cookie into current browser context
driver.get("https://www.investing.com/news/")

time.sleep(60) # wait for a minute to see if the popup happens
driver.quit()

运行这段代码,观察页面,不会显示注册弹窗。


替代解决方法: 使用已关闭注册弹出窗口的 Chrome 配置文件,也不会显示弹出窗口

from selenium import webdriver

options = webdriver.ChromeOptions() 
options.add_argument("user-data-dir=C:\Path") #Path to your chrome profile

如果你真的需要在没有这些方法的情况下关闭弹窗,用try/except定义一个检查函数。在执行任何操作之前,调用此函数检查是否有弹出窗口,然后关闭弹出窗口,将状态保存到某个变量(因此您不再检查它)。由于该函数具有 try/except,它不会引发异常,您的代码将 运行.