How to click on the X icon to close the iframe using Seleniumv3 and Python3

Viewed 1202

I am having difficulty closing iframe popup on https://www.kariyer.net/ using python3.

iframe

When I try to inspect the code inside browser it looks like the link is inside an <i> tag and there are no href inside that tag. My guess is that it's a javascript link and I'm not much of a javascript guy at all.

I couldn't find anything on google cause every situation that comes up on google, seems include either a button or an href tag.

iframe code inspection

Since it's a live website, I am not sharing html code but if you need it please let me know. I am fairly new to Selenium and any help would be appreciated. Thanks in advance.

2 Answers

As per the url you have shared to click() on the X icon you have to induce WebDriverWait for the frame to be available and switch to it and then again induce WebDriverWait for the desired element to be clickable and you can use the following solution:

  • Code Block:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait 
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("https://www.kariyer.net/")
    
    # xpath
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@class='sp-fancybox-iframe adaptive-resolution']")))
    
    # css_selector
    # WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.sp-fancybox-iframe.adaptive-resolution")))
    
    # xpath
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='element-content']/i[@class='fa fa-times element-close-button']"))).click()
    
    # css_selector
    # WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.element-content > i.fa.fa-times.element-close-button"))).click()
    
  • Browser Snapshot:

kariyer

Code below waits frame and switch to it, then clicks to close button and switch back to main. See selectors I used if you have problems to locate them.

WebDriverWait(driver, 10)
    .until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe.sp-fancybox-iframe")))
driver.find_element_by_css_selector("i.element-close-button").click()
driver.switch_to.default_content()

Most likely, you'll have to write custom handler to be able to skip different types of popups coming on first open the website. For example, you can put code above to try/catch to be able to skip without error if any other type of popup will appear.

Related