Search code examples
pythonseleniumxpathclickwebdriverwait

Selenium Python: How to click button


I'm trying to click

<div class="accBtn button buttonP" onclick="registerAcc()">Register</div>

if you visit krunker.io and inspect and then just ctrl f Register you should find it.

Here is my code:

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

and the error is "no such element"


Solution

  • The Krunker website uses AJAX calls.


    Solution

    To click on the element Register you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following locator strategies:

    driver.execute("get", {'url': 'https://krunker.io/'})
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@id='onetrust-accept-btn-handler']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='signedOutHeaderBar' and contains(., 'Login or Register')]"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='accBtn button buttonP' and text()='Register']"))).click()
    

    Note: You have to add the following imports :

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