There's a modal window on this page: https://shop.wegmans.com. It doesn't popup every time but it's frequent enough that I can reproduce this issue.
On the page I'm running the following code:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
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.common.exceptions import NoSuchElementException
option = webdriver.ChromeOptions()
option.add_argument('--disable-blink-features=AutomationControlled')
option.add_argument("start-maximized")
option.add_experimental_option(
"excludeSwitches", ["enable-automation"])
prefs = {"credentials_enable_service": False,
"profile.password_manager_enabled": False,
"useAutomationExtension": False}
option.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=option)
wait = WebDriverWait(driver, 20)
driver.maximize_window()
# Logging in
# ....
# ....
wait.until(EC.title_contains('Home'))
try:
driver.find_element_by_class_name("modal")
print("Modal Found")
except NoSuchElementException:
print("Modal not found")
Every time the page loads with the modal the div is there and every time the console prints Modal not found
.
The site is using Angular and React. I don't know if this is because of the way the DOM is generated.
How can I make Selenium see the modal so that I can close it?
CodePudding user response:
I tried 5-6 times
, but could not actually reproduce it. I believe you need to induce WebDriverWait
.
try:
wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "modal")))
print("Modal Found")
except NoSuchElementException:
print("Modal not found")
HTML of modal window will be more helpful.
CodePudding user response:
As the modal window on the page https://shop.wegmans.com doesn't popup every time, you can surround the click()
on the modal within a try-except{}
block with a specific timeout as follows:
from selenium.common.exceptions import TimeoutException
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, "modal"))).click()
print("Modal found and clicked")
except TimeoutException:
print("Modal wasn't found")