Home > Back-end >  how to click with selenium in python onclick without class, id or name
how to click with selenium in python onclick without class, id or name

Time:09-23

I'm trying to find a way to click on "X" button but I cannot find the way to click on this button.

Element copy:

<div style="cursor: pointer; float:right; border-radius: 3px; background-color: red; font-size: 10px; color: white; height: 15px; width:15px; line-height: 15px;" onclick="fecharModal();">X</div>

Xpath:

//*[@id="meu_modal"]/div

Css Selector:

#meu_modal > div

Tried:

driver.find_element_by_css_selector("a[onclick*=fecharModal]").click();

Imports:

from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.action_chains import ActionChains import timeenter code here

CodePudding user response:

Presuming that the xpath you provided is accurate, I suggest you try this code possibly this might work for you.

yourEle = driver.find_element_by_xpath("//*[@id='meu_modal']/div")
driver.execute_script("arguments[0].click();", yourEle)

CodePudding user response:

This seems to be an angular bases application, mostly WebDriverWait should do the job, but still below solution illustarte all the ways in Selenium to click a web element. Code trial 2 is more preferable and best practices.

I will use this xpath

//div[@onclick='fecharModal();' and text()='X']

Code trial 1 :

time.sleep(5)
driver.find_element_by_xpath("//div[@onclick='fecharModal();' and text()='X']").click()

Code trial 2 :

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@onclick='fecharModal();' and text()='X']"))).click()

Code trial 3 :

time.sleep(5)
button = driver.find_element_by_xpath("//div[@onclick='fecharModal();' and text()='X']")
driver.execute_script("arguments[0].click();", button)

Code trial 4 :

time.sleep(5)
button = driver.find_element_by_xpath("//div[@onclick='fecharModal();' and text()='X']")
ActionChains(driver).move_to_element(button).click().perform()

Imports :

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

PS : Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

  • Related