Reputation: 323
I'm trying to locate and click an element on my page but can't use the by.id method as the id's are generated and change per session. For most elements I can get around this by using xpath but there is a dropdown menu where this does not work. I can click the element containing the dropdown and it shows me the options. If I locate the element I need and copy it's xpath the test case won't function stating it can't find the xpath. Now next to the id the Element I'm trying to click also has a class. Problem is that this class is not unique, all menu items in the dropdown have the same class with a different text. What I would like to do is something like:
driver.findeElement(By.class("x-menu-item-text").equals("Unique text 1here").click()
The class "x-menu-item-text" is not unique but the text in this particular class is. I can't use the ID as this is automatically generated. The full code for the item or element I want to click is:
<a id="ext-comp-1035" class="x-menu-item" hidefocus="true" unselectable="on" href="#"><span id="ext-gen250" class="x-menu-item-text">Unique text 1 here</span></a>
<a id="ext-comp-1035" class="x-menu-item" hidefocus="true" unselectable="on" href="#"><span id="ext-gen250" class="x-menu-item-text">Unique text 2 here</span></a>
I'm using Selenium Webdriver with Eclipse (Java).
Allthough the answer provided seems to work on most pages and locations, there is a situation however where I can't get it to work. Can anyone advise? There is a page with buttons and I want to click one of these buttons. If I use the following statement:
driver.findElement(By.xpath("//*[@class=' x-btn-text' and text()='Add']")).click();
I get an error message
org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
If I look at the source I see:
<button class=" x-btn-text" id="ext-gen539" type="button">Add</button>
So the element is present and visible. I've tried adding a wait.until statement before the click statement but this does not work either:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@class=' x-btn-text' and text()='Toevoegen']")));
driver.findElement(By.xpath("//*[@class=' x-btn-text' and text()='Toevoegen']")).click();
Extra information: could this problem be because I'm looking for an element that is located in a popup?
Upvotes: 2
Views: 2008
Reputation: 599
You can use xpath locator https://newcircle.com/bookshelf/selenium_tutorial/locators
By.xpath("//span[@class='x-menu-item-text' and text()='Unique text 1here']")
Upvotes: 2