Obus
Obus

Reputation: 51

Selenium: finding elements in searchContext

everyone! I'm stuck with following problem: There is some

SearchContext searchContext;
By by;

which could be WebDriver or WebElement. Assume that both of them are already initialized (and we don't know how); Now we want to find elements with such xpath, seems to do following

List<WebElement> elements = searchContext.findElements(by);

But, if searchContext is WebElement and

by = By.xpath("//div");

it wouldn't work! (no elements would be found), because we need to do

by = By.xpath("./div");

(see Locating child nodes of WebElements in selenium) But, how i've mentioned, we know nothing about how by was initialized;

So, my question is: is there any way to find elements properly despite the problems above? I've got two variables: by and searchContext, and I should to find specified element in searchContext.

Upvotes: 2

Views: 7169

Answers (2)

Obus
Obus

Reputation: 51

As I understand, there is now way to do it. Only way to do it - is manually specify By.xpath properly:

By child = By.xpath("/div");
By descendant = By.xpath("//div");

in case of WebDriver.isAssignableFrom(searchCOntext.getCLass()), and

By child = By.xpath("div");
By descendant = By.xpath(".//div");

in case of WebElement.isAssignableFrom(searchCOntext.getCLass()). IMHO, it's bad.

Upvotes: 0

Pavel Janicek
Pavel Janicek

Reputation: 14748

You can do it in some helper method which will throw Exception if this happens

public List<WebElement> returnSearchContext(By by, SearchContext searchContext){
  List<WebElement> elements = searchContext.findElements(by);
  if (elements.getSize()>0){
     return elements;}
   else{
     throw new ElementNotFoundException();
   }
}

I am writing this without access to any IDE, so I might do some errors in my example code. For instance, I think that the exception will need some parameters. But I hope you get the idea.

Upvotes: 0

Related Questions