I'm trying to get a program to click a button using selenium.
I've tried many different find_elements_by...()
and many different arguments, but I can't figure out which find_element_by*()
. I need to use and what should be in the argument
Where is what I'm trying to click:
<article onclick="mainPrincipalPage.PerformCallback('Registro');">
<div class="imageBox">
<img src="../Images/iconRegistroHorario.svg">
</div>
<div class="titleBox">
<span>Registro horario</span>
</div>
</article>
CodePudding user response:
try this
browser.find_element_by_xpath('just copy and paste the Xpath').click()
See this picture :
CodePudding user response:
In order to locate a web element you can use any unique combination of any element attribute values, not only id
or CSS Selector
.
For example to locate and click the article
element you can use this XPath locator:
driver.find_element_by_xpath("//*[contains(@onlick,'mainPrincipalPage.PerformCallback(" "Registro" ")')]")
To click on span
containing the Registro horario
text you can simply use
driver.find_element_by_xpath("//span[text()='Registro horario']")
etc.
CodePudding user response:
You can use CSS Selector method to select an element without ID. All you need to do is seeing the HTML as a folder, with other folders inside. You need to find a tag that you can identify, then find your way to the desired element. This way, you can locate any element, even if another element with the same tag exist.
You can find every CSS selector here
By the way, you should use By method by importing it: from selenium.webdriver.common.by import By
:
driver.find_element(By.CSS_SELECTOR, 'article[onclick="mainPrincipalPage.PerformCallback('Registro');"]').click
In your case, without By method, it should look like this:
driver.find_element_by_css_selector( 'article[onclick="mainPrincipalPage.PerformCallback('Registro');"]').click
CodePudding user response:
To click on the Image Box within the <article>
you can use either of the following Locator Strategies:
Using
css_selector
:driver.find_element(By.CSS_SELECTOR, "article[onclick^='mainPrincipalPage']>div.imageBox>img").click()
Using
xpath
:driver.find_element(By.XPATH, "//article[starts-with(@article, 'mainPrincipalPage')]/div[@class='imageBox']/img").click()
Ideally, to click on the element you need to induce WebDriverWait for the element_to_be_clickable()
and you can use either of the following Locator Strategies:
Using
CSS_SELECTOR
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "article[onclick^='mainPrincipalPage']>div.imageBox>img"))).click()
Using
XPATH
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//article[starts-with(@article, 'mainPrincipalPage')]/div[@class='imageBox']/img"))).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