Search code examples
pythonhtmlselenium-webdriver

Python selenium: Impossible to close a frame using xpath or class_name


I'm trying to close a frame on this page.

What I want is to click in here:

enter image description here

It seems to be easy, but so far the following code (which should work) has failed:

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

driver = selenium.webdriver.Chrome()
driver.maximize_window()
driver.get('https://www.bvc.com.co/variable-income-local-market/cemargos?tab=issuer-information')

#X(close) bvc frame
xpath = '//*[@id="__next"]/div/div[1]/div/div[1]/div/div/div/div/div[3]/div/div/div/div[3]/div[2]/span'
class_name = 'sc-843139d2-14 iVPGqd'

# Trying with XPath
if 1:
    try:
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath))).click()
    except:
        driver.find_element(By.XPATH, xpath).click()

# Trying with class_name
if 1:
    try:
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, class_name))).click()
    except:
        driver.find_element(By.CLASS_NAME, class_name).click()

The output using XPath:

raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 
Stacktrace:
#0 0x64a95375031a <unknown>
...

The output using class_name:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".sc-843139d2-14 iVPGqd"}

Solution

  • when you do

    driver.find_element(By.CLASS_NAME, 'sc-843139d2-14 iVPGqd')
    

    selenium translates (poorly, by adding one dot) your class name into a selector, so it becomes

    driver.find_element(By.CSS_SELECTOR, '.sc-843139d2-14 iVPGqd')
    

    which means: find a iVPGqd tag (yes tag) contained within something with a class sc-843139d2-14. you don't want that. if you want to specify two classes for the same element you must collate them with no spaces between and use the proper locator CSS_SELECTOR

    driver.find_element(By.CSS_SELECTOR, '.sc-843139d2-14.iVPGqd')