Why does my xPath locator only work once?
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/ul/li/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.
Let's take a look at your xpath selector:
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'").