Home > Software engineering >  Click on a webelement using Selenium and onclick attribute
Click on a webelement using Selenium and onclick attribute

Time:07-23

I am having trouble using selenium and using CSS select for onclick.

The HTML code looks like this:

<div  onclick="login.LoginCACSynchro('SYNCHRO');">

My current code looks like this:

Synchro = driver.find_element_by_css_selector("a[onclick^='login.LoginCACSynchro('SYNCHRO');']")

Not sure what I a doing wrong here, any help would be very appreciated!


Update

It looks like it wants to work but I am getting this error:

Message: element click intercepted: Element <div  onclick="login.LoginCACSynchro('SYNCHRO');">...</div> is not clickable at point (651, 543). Other element would receive the click: <div id="loader2" style="opacity: 0.627993;">...</div> (Session info: chrome=103.0.5060.134)

CodePudding user response:

To click on the element you can use either of the following locator strategies:

  • Using css_selector:

    driver.find_element(By.CSS_SELECTOR, "div.hexagon.pointer[onclick^='login'][onclick*='LoginCACSynchro'][onclick*='SYNCHRO']").click()
    
  • Using xpath:

    driver.find_element(By.XPATH, "//div[@class='hexagon pointer' and starts-with(@onclick, 'login')][contains(@onclick, 'LoginCACSynchro') and contains(@onclick, 'SYNCHRO')]").click()
    

Update

As per your comment update to click on the element:

  • First induce WebDriverWait for the invisibility_of_element

  • Then induce WebDriverWait for the element_to_be_clickable() as follows:

    • Using CSS_SELECTOR:

      WebDriverWait(driver, 30).until(EC.invisibility_of_element((By.CSS_SELECTOR, "div#loader2")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.hexagon.pointer[onclick^='login'][onclick*='LoginCACSynchro'][onclick*='SYNCHRO']"))).click()
      
    • Using XPATH:

      WebDriverWait(driver, 30).until(EC.invisibility_of_element((By.XPATH, "//div[@id='loader2']"))) 
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='hexagon pointer' and starts-with(@onclick, 'login')][contains(@onclick, 'LoginCACSynchro') and contains(@onclick, 'SYNCHRO')]"))).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
    
  • Related