2

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.

Community
  • 1
  • 1
Obus
  • 51
  • 1
  • 6

2 Answers2

0

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.

Pavel Janicek
  • 14,128
  • 14
  • 53
  • 77
  • Thank you for reply!=) Unfortunately, this wouldn't solve the problem, it's just a way to handle a failure. It is my fault - formulation of my question wasn't clear enough. I make it more concrete. – Obus Aug 06 '12 at 11:32
  • stupid me :) Is the issue only "that easy"? Meaning - when the search context is WebElement, do you really need to find only child DIV, or is it complicated? – Pavel Janicek Aug 06 '12 at 13:58
0

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.

Obus
  • 51
  • 1
  • 6