DDUffy
DDUffy

Reputation: 95

How do I make selenium find an element whos Id changes

So I am automating with selenium and running into an issue where everytime I refresh a page, the element ID changes, no matter if I copy XPATH, CSS Selector, ID, they all have a number in them that changes.

so the code I'm using is simple, I just want to click the button which I can accomplish with

browser.find_element(by=By.CSS_SELECTOR, value='*VALUE HERE*').click()

But I don't know what to put as the value. Here is the HTLM code

<a class="x4-tab x4-unselectable x4-box-item x4-tab-default x4-noicon x4-tab-noicon x4-tab-default-noicon x4-top x4-tab-top x4-tab-default-top x4-tab-after-title x4-active x4-tab-active x4-tab-default-active x4-top-active x4-tab-top-active x4-tab-default-top-active" hidefocus="on" unselectable="on" id="tab-1965" tabindex="0" data-ui-comp-name="wm-np-tab-wrkstn" style="right: auto; left: 66px; margin: 0px; top: 0px;">
<span id="tab-1965-btnWrap" role="presentation" class="x4-tab-wrap" unselectable="on">
  <span id="tab-1965-btnEl" class="x4-tab-button" role="presentation">
    <span id="tab-1965-btnInnerEl" class="x4-tab-inner x4-tab-inner-center" 
    unselectable="on">Workstations</span>
    <span role="presentation" id="tab-1965-btnIconEl" class="x4-tab-icon-el  " unselectable="on" 
    style="">
  </span>
</span>
</span>
</a>

If you look at the HTML, anywhere you see that number 1965, that number will change if the page is refreshed. How do I make selenium find this element no matter what that number is?

Also, not sure if this matters but this is all in an iframe which I have selenium target by using

frame1 = browser.find_element(by=By.CLASS_NAME, value='defaultView')

browser.switch_to.frame(frame1)

Also, another problem is that HTML code is almost identical to other buttons, the only differences between the buttons is that number (that changes) and where is says "Workstations". Here is an example of another button that is next to it, this one is for servers.

<span id="tab-1964-btnWrap" role="presentation" class="x4-tab-wrap" unselectable="on">
  <span id="tab-1964-btnEl" class="x4-tab-button" role="presentation">
    <span id="tab-1964-btnInnerEl" class="x4-tab-inner x4-tab-inner-center" 
    unselectable="on">Servers</span>
    <span role="presentation" id="tab-1964-btnIconEl" class="x4-tab-icon-el" 
    unselectable="on" style="">
  </span>
</span>
</span>
</a>

Upvotes: 1

Views: 1563

Answers (1)

pL3b
pL3b

Reputation: 1353

You can use XPath for this:

browser.find_element(by=By.XPATH, value="//span[starts-with(@id, 'tab-') and contains(@id, '-btnEl')]").click()

Upvotes: 3

Related Questions