Home > other >  How to find the element using Selenium
How to find the element using Selenium

Time:04-28

I have an element that clears a query after the query is made, but I can't get selenium to locate it.

Here is the xpath for the element:

/html/body/main/div/section[1]/div/a[2]

This is the html for the element:

<a onclick="onClearClicked()" >clear</a>

Things that I have tried:

  • Finding by using the whole xpath, css selector, class name, text

  • Using css to find all buttons on the page and iterating over them until I find the right one (it doesn't find any buttons with text)

buttons = mydriver.find_elements_by_css_selector("button")
for button in buttons:
    print(button.text)
    if button.text.strip() == "clear":
        button.click()```
  • Exiting the iframe I was in before and using the full xpath
driver.switch_to().defaultContent()

Edit: I also noticed it doesn't seem to be 'included' in the drop down like other elements (no drop down arrow next to it unlike the other elements within the same div)

I have a work around that involves quitting the driver and reopening it for every query, but this would involve logging in and navigating to the right page every time and I'd much rather be able to just use the clear button.

CodePudding user response:

Your html doesn't have any "button" element; it's an "a" (hyperlink) element. So, you should do:-

buttons = mydriver.find_elements_by_css_selector("a")

CodePudding user response:

Using full xpath not a good way , so try the following code:

buttons =driver.find_elements_by_css_selector("[class='btn btn--secondary btn--sm']")
for button in buttons:
    print(button.text)
    if button.text.strip() == "clear":
        button.click()

CodePudding user response:

driver.find_element(By.XPATH,"//a[.='clear']").click()

If you want to click the element with the text clear you can just look for an a tag with that text.

CodePudding user response:

The element is a <a> tag which have the innerText as clear

<a onclick="onClearClicked()" >clear</a>

Solution

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

  • Using LINK_TEXT:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "clear"))).click()
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.btn--secondary.btn--sm[onclick^='onClearClicked']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='btn btn--secondary btn--sm' and starts-with(@onclick, 'onClearClicked')]"))).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