Take the 2-minute tour ×
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. It's 100% free, no registration required.

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.

share|improve this question
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

2 Answers 2

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'").

share|improve this answer
    
I think this is correct, probably the selector changed due to the action earlier. –  Niels van Reijmersdal May 6 at 14:12

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.

share|improve this answer
    
Forward slash is not an escape character in Java. Backslash is an escape character. –  user246 May 4 at 21:21
    
True, thanks for looking out. Removing that portion. –  PaulDonny May 5 at 12:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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