pythonselenium-webdriverbots

Click on button on async website - Unable to locate element: {"method":"css selector","selector":".Icon__oBwY4"}


I am trying to click over this button (which shows when the website is being accessed for the first time) from this website (https://www.popmart.com/sg/user/login) through the use of selenium :

enter image description here

I am trying to use find_element() function and I can see on the website elements that the class is written as expected along its name. However when I try the following:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time 
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

print("Imported packages successfully!")

########### launch website ##################

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.get("https://www.popmart.com/sg/user/login")

time.sleep(10)


driver.find_element(By.CLASS_NAME,  "Icon__oBwY4").click()

I got the following error:

elenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".Icon__oBwY4"}

Do you know if there's any other workaround to be able to click this button through selenium?


Solution

  • This is the relevant HTML,

    <div class="index_closeContainer__vm5Us">
      <img src=".../close.png" class="index_closeIcon__oBwY4">
    </div>
    

    NOTE: I shortened the src to make it easier to read.

    If it were me, I would use the CSS selector below because the full class name looks like it has some randomly generated characters at the end, class="index_closeIcon__oBwY4", that may change in future updates to the site thus breaking your script. I don't know for sure, but I'm assuming this will work even after updates

    img[class^='index_closeIcon__']
    

    Using a WebDriverWait, the code would be

    wait = WebDriverWait(driver, 10)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "img[class^='index_closeIcon__']"))).click()