user7365333
user7365333

Reputation:

How do I find one element after using Findelements in Selenium?

I'm trying to create this global method that click on this link called "Categories". The ID (t_166) is dynamic, Xpath (//*[@id="t_166"]) and "copy selector" (#t_166) use the id number also so they won't work.

So, I'm left with the html:

enter image description here

I figured class would be a good candidate. So... to start:

var categorymenu = driver.instance.findelement(by.classname("fontMediumBigColorGrey navigatorLinkClicked z-label")

And then I want it to find the category one and click on it, something like: categorymenu.getattribute(category).click();

Two problems.

Problem 1: The link's class changes depending if you've visited it previously, or the "linkclicked" part in it. It becomes "fontMediumBigColorGrey z-label" if you haven't been on it. Question: it won't be able to find categories if the class is different. How would I handle this?

Problem 2: There are many other links (like users) that use the same classes, so shouldn't I be using findelements and then isolate it by an attribute (category is this case) But findelements doesn't seem to be able to use getattribute (because there are many of them) so how do I cover that part?

Thanks!

Upvotes: 4

Views: 1485

Answers (2)

Happy Bird
Happy Bird

Reputation: 1142

In case you want to see if the span has the fontMediumBigColorGrey class:

var categorymenu = driver.instance.findelement(by.xpath("//span[contains(@class, 'fontMediumBigColorGrey')]")

In case you want to see if the text is equal to "Categories":

var categorymenu = driver.instance.findelement(by.xpath("//span[text()='Categories']")

A trick that I sometimes use, and could be useful for you too - if you're using Chrome, open the console and edit the HTML in such a way that you delete the "id" tag. Then, right click and choose 'Copy > Copy XPath'. This will copy the XPath but neglect the ID (because you can't use it since it's dynamic).

Upvotes: 0

Andersson
Andersson

Reputation: 52665

You can use search by XPath to find your element:

var categorymenu = driver.instance.findelement(by.xpath("//span[text()='Categories']")

In code above you search for span element with "Categories" as its text value

Also you can try to ignore dynamically changing part of id attribute in following way:

var categorymenu = driver.instance.findelement(by.xpath("//div[starts-with(@id, 't_')][substring-after(@id, '-')='cave']/span")

Above code should search for span that is child of div with id="t_XXXX-cave" where XXXX is ignored part

Note You should also be aware that you will not be able to complete categorymenu.getattribute(category).click(); as categorymenu.getattribute(category) (actually categorymenu.GetAttribute(category)) returns just a string value

Upvotes: 2

Related Questions