简体   繁体   中英

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

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 class="jss2383">
  <button class="MuiButtonBase-root-2225 MuiButton-root-2198 MuiButton-contained-2206 MuiButton-containedPrimary-2207" tabindex="0" type="button">
   <span class="MuiButton-label-2199">Refresh</span>
   <span class="MuiTouchRipple-root-2395"></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;

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

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

These classnames ie 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM