Home > OS >  How to identify an element by classname that keeps changing using Selenium
How to identify an element by classname that keeps changing using Selenium

Time:08-20

I am trying to locate a buttons element, but every time my test run the element keeps on changing name. The class keeps changing the last digits. For Example, jss2383 to jss4132 as well as all elements within the button class. My alternative solution is by using the xpath to find it by text.

<div >
  <button  tabindex="0" type="button">
   <span >Refresh</span>
   <span ></span>
  </button>
</div>

What I have so far to find the element is the following. The reason I want to locate the element by class name is because the button can either be a refresh or an import.

@FindBy(xpath="//span[text()='Refresh']")
WebElement refreshButton;

CodePudding user response:

As the class value changes dynamically, So you can use contains function

@FindBy(xpath="//span[contains(@class,'MuiButton-label')]")

CodePudding user response:

These classnames i.e. jss2383, jss4132 are dynamically generated and is bound to chage sooner/later. They may change next time you access the application afresh or even while next application startup. So can't be used in locators.


Solution

As you mentioned "...the button can either be a refresh or an import..." you can use either of the following locators:

  • Using xpath1:

    @FindBy(xpath="//button//span[text()='Refresh' or text()='Import']")
    WebElement refreshImportButton;
    
  • Using xpath2:

    @FindBy(xpath="//button//span[starts-with(@class, 'MuiButton-label')][text()='Refresh' or text()='Import']")
    WebElement refreshImportButton;
    
  • Related