Hello I need to click on a href link but it doesn't have any class, id, text or anything at all.
<div>
<a href="/ad/repost/id/2109701">
<span>Réafficher</span>
<i >
</i>
</a>
I've tried the following and multiple other things.
Link = driver.find_element((By.XPATH, '//*[@id="body"]/div[4]/div[3]/div[1]/div[3]/div[1]/a/span'))
But it throws an error.
I also have the same issue with an input button :
<div >
<input type="button" value="Fermer">
</div>
help >_<
CodePudding user response:
You can locate the href element with the following locators:
"//a[contains(@href,'/ad/repost/id/2109701')]"
or
"//a[./span[text()='Réafficher']]"
The input element can be located with
"//input[@value='Fermer']"
I can't be 100% sure about uniqueness of the locators above without seeing the actual web page HTML
CodePudding user response:
The href attribute is part of the parent A tag, which also have a descendant SPAN which contains the text Réafficher. So invoking click on the SPAN would also result as similar as clicking the A tag with the href attribute.
To click() on the element with text as Réafficher you can use either of the following Locator Strategies:
Using css_selector:
driver.find_element(By.CSS_SELECTOR, "a[href$='2109701'] span").click()Using xpath:
driver.find_element(By.XPATH, "//a[@href]//span[text()='Réafficher']").click()
Ideally to click on a clickable 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, "a[href$='2109701'] span"))).click()Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@href]//span[text()='Réafficher']"))).click()
Similarly, to click on the <input> button you can use either of the following Locator Strategies:
Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.btn-orange.modal-close[value='Fermer']"))).click()Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='btn-orange modal-close' and @value='Fermer']"))).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
