我正在从多个网站获取数据,并且遇到了一个弹出窗口的网站(见下图)。我尝试了多种方法,例如检查警报或获取驾驶员的车窗,以便我可以切换到它并关闭它。我真的很困惑,似乎找不到解决办法。我见过解决方案,但这些解决方案带有警报。有人有想法吗?
在 Selenium 中,您可以指定等待给定元素,因此如果这是已知的弹出窗口,则:
我尝试了多种方法。所有这些都成功了,因为我在
time.sleep(10)
之后添加了 driver.get('url')
。
from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(executable_path="path to chromedriver.exe")
driver.maximize_window()
driver.implicitly_wait(30)
driver.get("https://satellitenewsnetwork.com/")
time.sleep(10) # None of the below method works if this is removed.
wait = WebDriverWait(driver,30)
driver.switch_to.frame(driver.find_element_by_id("ml-webforms-popup-2207054"))
# First:
closepopup = driver.find_element_by_xpath("//div[@class='mailerlite-popup']/a")
print(closepopup.get_attribute("class"))
closepopup.click()
# Second:
# popup = wait.until(EC.presence_of_element_located((By.XPATH,"//div[@class='mailerlite-popup']"))) # Tried with visibility_of_element_located too.
# print(popup.get_attribute("class"))
# closepopup = driver.find_element_by_xpath("//div[@class='mailerlite-popup']/a")
# print(closepopup.get_attribute("class"))
# closepopup.click()
# Third:
# closepopup = driver.find_element_by_xpath("//div[@class='mailerlite-popup']/a")
# print(closepopup.get_attribute("class"))
# driver.execute_script("arguments[0].click();",closepopup)
#
# Fourth:
# closepopup = driver.find_element_by_xpath("//div[@class='mailerlite-popup']/a")
# print(closepopup.get_attribute("class"))
# ActionChains(driver).move_to_element(closepopup).click().perform()
time.sleep(5)
driver.quit()