Search code examples
pythonselenium-webdriverweb-scrapingwebdriver

How to click on the age verification popup window in Selenium?


I am trying to use Selenium to search something in Aliexpress, but when I search for some products, for example, when I type "test," I will have a popup window that requests my age verification, as shown below: The popup window

I am trying to click on "I AM OVER 18" by driver, but nothing works

The code I used is:

def aliexpress_driver():
    url = 'https://www.aliexpress.com/'
    global browser
    browser = webdriver.Chrome()
    browser.get(url)


def search_for(product):
    aliexpress_driver()
search = browser.find_element("id","search-key").send_keys("test")
    SearchBtn_xpath = r'//*[@id="form-searchbar"]/div[1]/input'
    search_btn = browser.find_element(By.XPATH,SearchBtn_xpath)

    browser.execute_script("arguments[0].click();", search_btn)
    time.sleep(10)

    p = r'/html/body/div[8]/div[2]/div/div[2]/div/div[1]'
    browser.find_element(By.XPATH,p ).click
    print("Clicked")

I always got the error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[8]/div[2]/div/div[2]/div/div[1]"}

Note: I tried the following things:

1- WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, p))).click()

2- I also tried to use CSS selector, using class name

The HTML element is : <div class="law18--btn--29ue4Ne law18--left--2XI39FE" data-spm-anchor-id="a2g0o.productlist.0.i23.4ac93c4fzXPnR5">I AM OVER 18 </div>

can you help please?


Solution

  • you can simply click on I AM OVER 18 tab by:

    1. wait for the web element to get visibly located.
    2. then find the element using CSS_SELECTOR and click.

    Here's how you may try:

    from time import sleep
    from selenium.webdriver import Chrome, Keys
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.wait import WebDriverWait
    import selenium.webdriver.support.expected_conditions as EC
    
    def aliexpress_driver():
        url = 'https://www.aliexpress.com/'
        browser = Chrome()
        browser.get(url)
        return browser
    
    def search_for(product):
        browser = aliexpress_driver()
        wait = WebDriverWait(browser, 10)
    
        search = wait.until(EC.visibility_of_element_located((By.ID, 'search-key')))
        search.send_keys(product)
        search.send_keys(Keys.ENTER)
    
        # wait for the element to get located to click
        wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.law18--btn--29ue4Ne.law18--left--2XI39FE'))).click()
        print("Clicked")
        sleep(5)
    
    search_for('test')
    

    output:

    Clicked