开发者

Selenium Api, Selenium locators and regex

In my page I have some ids like "foo:searchResults12345" that are composed of a static part ("foo:searchResults" and a dynamic rendered one - one or more numbers. I want to retrieve every id that contains the static part "foo:searchResults", ignoring the dynamic one. I am thinking at using regex for the pattern text, but the problem is that I cannot find any method in Selenium Api to help me with this, such as selenium.getAllIdsInPage(). Anybody had the sam开发者_运维知识库e problem and figured out a solution?


I would recommend combining getXpathCount with a loop to iterate through each match. For example the following xpath should return the total number of matching nodes when used with getXpathCount

//*[starts-with(@id, 'foo:searchResults')]

You should then be able to loop through each match using the following example XPath:

/descendant::*[starts-with(@id, 'foo:searchResults')][1]

Where 1 would be replaced by the current count in the loop.

Below is an example in Java that should print the matching IDs to system.out:

@Test
public void outputDynamicIds() {
    selenium.open("http://www.example.com/");
    int elementCount = selenium.getXpathCount("//*[starts-with(@id, 'foo:searchResults')]").intValue();
    for (int i = 1; i < elementCount+1; i++) {
        System.out.println(selenium.getAttribute("/descendant::*[starts-with(@id, 'foo:searchResults')][" + i + "]@id"));
    }
}


Another way to go is to use a custom Location Strategy. I am doing this in my current project and it works fine.

In your particular case you can write a custom strategy that checks if the id attribute of each element starts with the locator string (the static part in your example) and return this element if that is so.

I think this approach is much cleaner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜