Home > front end >  Can't get selenium to find button
Can't get selenium to find button

Time:04-27

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

Here is the xpath for the button:

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

This is the html for the button:

<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()

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.

  • Related