Home > Back-end >  How to locate the button element using Selenium?
How to locate the button element using Selenium?

Time:07-06

I need to find the xpath of the help button for my automation tests.
Here is the HTML element:

<button data-component-id="nokia-react-components-iconbutton" tabindex="0"  mode="dark" type="button" xpath="1"></button>
<svg  viewBox="0 0 24 24" xpath="1">
</svg>

I tried with this XPath, but it didn't work:

//*[@data-component-id="nokia-react-components-iconbutton"]//svg[contains(@class,"HelpOutline")]

CodePudding user response:

If you want to select the <button> element before the <svg>, try the following XPath:

//*[@data-component-id="nokia-react-components-iconbutton" and following-sibling::svg[1][contains(@class,"HelpOutline")]]

CodePudding user response:

Try this XPath to locate button:

'//*[name()="svg" and contains(@class,"HelpOutline")]/preceding-sibling::button'

Note that svg tag is not a part of standard HTML-namespace, so //svg won't work. You need to use //*[name()="svg"] instead

CodePudding user response:

The <button> element itself should be clickable and both the locator strategies should work:

  • css_selector:

    button[class*='HelpButton'][data-component-id='nokia-react-components-iconbutton']
    
  • xpath:

    //button[@data-component-id='nokia-react-components-iconbutton' and contains(@class, 'HelpButton')]
    

However, as the element is a React element so 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 Java and xpath:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@data-component-id='nokia-react-components-iconbutton' and contains(@class, 'HelpButton')]"))).click();
    
  • Using Python and css_selector:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[class*='HelpButton'][data-component-id='nokia-react-components-iconbutton']"))).click()
    
  • Note: For Python clients 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