Can't switch to iframe and close the frame in Selenium using Python
Answer a question
After multiple unsuccessful attempts to try and grab details from the website (https://www.chemist.co.uk/) I realized that there is an iframe that appears after a few seconds and that the event only happens once, when the website is opened. However, I find it difficult to handle the iframe, I tried various methods like finding the iframe based on index and id as well, as the iframe has no name. From my observation this only happens once I open the website. Can someone help me figure out what am I doing wrong?
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
currentdir = os.getcwd()
chrome_options = Options()
# chrome_options.add_argument('--headless')
chrome_options.add_argument("--disable-notifications")
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome(executable_path=f"{currentdir}/chromedriver.exe", options=chrome_options)
# driver.maximize_window()
driver.implicitly_wait(20)
driver.get("https://www.chemist.co.uk/")
time.sleep(5)
# driver.switch_to.frame(1)
iframe = driver.find_element_by_id("AWIN_CDT")
driver.switch_to.frame(iframe)
driver.find_element_by_xpath("//a[@data-trigger='dismiss.close']").click()
driver.switch_to.default_content()
Answers
Instead of using time.sleep use explicit wait for iFrame to appear and then switch to it. Also there are four iframes in your page. And the pop up is not inside the iframe with ID as AWIN_CDT rather it is inside 2nd frame with below infomation:
<iframe scrolling="no" style="border: none; height: 1px; width: 100%; min-height: 100%; display: inline !important;"></iframe>
So in order to close the pop up you need to switch to this frame.
driver.get('https://www.chemist.co.uk/')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@style,'border: none; height')]")))
driver.find_element_by_xpath("//a[@data-trigger='dismiss.close']").click()
driver.switch_to.default_content()
You need to import below:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
更多推荐

所有评论(0)