0

I am learning Java to automate testcases using WebDriver. As for now I was using Selenium IDE. I have a scenario. In date picker on selecting date, based on the current date and time-future timeslots will be displayed for booking appointments. If current date and time is march 7-2PM, after selecting date, timeslots will apper after 2PM like 2.15,3 etc.. In IDE, I used the locator as //div[4]/ul/li[2]/a. This picks the first item in the list everytime. But when I use the same in WebDriver, only 1 time, it picks the slot. The second time it fails. Any suggestions.

  • 1
    Make sure your table looks exactly the same as the first time. Maybe the fact that you chose the first slot somehow changed the whole table. – Eugene S Sep 4 '14 at 2:42
1

Let's take a look at your xpath selector:

//div[4]/ul/li[2]/a

This says that you want to find the fourth div on the page, under which there's a list. Then pick the second item in the list's first hyperlink.

This is incredibly brittle; if selecting a time slot adds another div to the page, say, one indicating that the slot isn't free, suddenly the xpath breaks. I suspect that your selection of one slot has changed the underlying HTML so that that selector no longer works.

Do any of the elements have IDs on them? Those will not change when other elements are added or removed. Barring that, can you put together a CSS selector that takes into account classes? Something like "div.timeselect ul li:nth-child(2) a" is already more robust, even though all I changed was the top element (instead of "fourth div on the page", it's "div with a class of 'timeselect'").

  • I think this is correct, probably the selector changed due to the action earlier. – Niels van Reijmersdal May 6 '15 at 14:12
0

I don't understand the 'it works the first time but not the second time' portion.

A way to handle this would be:

List<WebElement> items = driver.findElements(By.cssSelector("ul li"));
if ( items.size() > 0 ) {
  for ( WebElement we: items ) {
   System.out.println( we.getText() );
  }
}

The XPath method would be a better way to handle it though. What would be changing from the first to the second etc etc.

  • Forward slash is not an escape character in Java. Backslash is an escape character. – user246 May 4 '15 at 21:21
  • True, thanks for looking out. Removing that portion. – Paul Muir May 5 '15 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.