0

I wonder how to return an empty List when i try to find some WebElement but nothing found. Of course i want to avoid crash so this is what i have try:

def getList(): List[WebElement] = {

    try {
      driver.fineElements(By.xpath("bla bla))
    }catch{
      case e: TimeoutException => // What should i put here ???
    }
  }
8
  • 1
    Duplicates this stackoverflow.com/a/6521834/21755 even more closely Commented Jun 16, 2016 at 14:01
  • 1
    Possible duplicate of WebDriver: check if an element exists? Commented Jun 16, 2016 at 16:08
  • 1
    The accepted answer is wrong.. it doesn't even work. Please accept Mobrockers answer. Commented Jun 30, 2016 at 23:56
  • 1
    Well, it works, in that there isn't an exception so there's no need to catch one. I'd delete it, though, as it doesn't really address the question, except that since it's accepted i can't :(. Commented Jul 1, 2016 at 6:53
  • 1
    I've flagged my answer for a moderator to delete Commented Jul 1, 2016 at 7:33

1 Answer 1

5

Edit:

I didn't notice you're using scala and not java, apologies, however it works the same in Scala. From the scala docs:

The findAll method returns an immutable IndexedSeq of all matching elements. If no elements match the query, findAll returns an empty IndexedSeq.

It already returns an empty list if no elements are found, and will not cause an exception.

The scala findAll method will do the same.

If you are not using scalatest but rather the Java selenium package, the same is still true. findElements will return an empty list when no elements are found and will never ever throw a TimeoutException.

Sign up to request clarification or add additional context in comments.

4 Comments

The OP isn't using findAll
There is no fineElement in selenium... From what I can gather from the docs, scala can use either findElements or findAll, they're the same. In both cases it will return an empty list and this try catch exception will never work as findElements or findAll do not throw an exception..
OK, gotcha. Since the OP specifies that getList returns a List[WebElement] we can assume he's using findElements, not findElement. So it will return an empty list as you say
It's kinda silly to create a function for this... it's a one-liner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.