Selenium handling List with java - java

Hi i have written this code . Now for date part it works as expected but for time part neither it is giving any exception nor it is printing time slots .
URL:-https://www.dineout.co.in/delhi/boa-village-civil-lines-north-delhi-21335
WebDriver driver;
String datee="";
String t="";
public RDP(WebDriver ldriver){
this.driver=ldriver;
}
#FindBy(how=How.XPATH,using="//input[#class='form-control']")
WebElement Time_selector;
#FindBy(how=How.XPATH,using="//*[#class='do do-calender-icon']")
WebElement calender;
public void logged_in_user_booking() throws InterruptedException
{
calender.click();
Thread.sleep(4000);
List<WebElement> dates= driver.findElements(By.cssSelector("ul.days li"));
//System.out.println(dates);
for(int i=0 ;i<dates.size();i++)
{
datee = dates.get(i).getText();
if(datee.equalsIgnoreCase("31"))
{
dates.get(i).click();
break;
}
}
List<WebElement> time_slots = driver.findElements(By.cssSelector("div.timings-wrap ul li"));
for(int j=0 ;j<time_slots.size();j++)
{
t = time_slots.get(j).getText();
System.out.println(t);
/* if(t.equalsIgnoreCase("03:00 pm"))
{
time_slots.get(j).click();
break;
}
*/
}

The time slots take some time to load, so if you didn't set implicitlyWait driver.findElements won't wait for any element to exist and will return an empty list. Adding implicitlyWait, one time right after the driver instantiation, should solve this problem (you should add it anyway).
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
You can also use explicit wait with Expected Conditions
WebDriverWait wait = new WebDriverWait(driver, 10);
List<WebElement> time_slots = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("div.timings-wrap ul li")));

Related

Element is not clickable in selenium java (chrome driver)

I am getting exceptions, when i am trying to click on Edit Criteria. Please someone can help me as
public void selectCriteriaFromWorklistsOptions() {
waitABit(Constants.medium);
for (int i = 0; i < 3; i++) {
try {
WebElement dropDown = getDriver().findElement(By.cssSelector(div.nav-menu__group > ul:nth-child(2) > li:nth-child(1) > button:nth-child(1)));
dropDown.click();
break;
} catch (Exception e) {
logger.debug((e.getMessage()));
}
}
}
Also, I tried this also -
WebElement element = waitForCondition().until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Edit criteria')])")));
element.click();
Wait for this element to become clickable.
And try using the following css selector:
.bttn-menu"
Or:
.nav-menu_bttn>.bttn-menu
Try 2:
button[bss-bttn-menu]
Try 3:
It should look like this in Java:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(.nav-menu_bttn>button[bss-bttn-menu]")));
Check the amount of underscores _ by yourself. Probably there are two of them.

Why is this WebElement not returning the full xpath?

I have several WebElements such that executing the following
List<WebElement> customers = driver.findElements(By.xpath("//div[#id='Customers']/table/tbody/tr"));
System.out.println(customers.size());
would print 5.
So then why does the following code
List<WebElement> customers = driver.findElements(By.xpath("//div[#id='Customers']/table/tbody/tr"));
for (WebElement customer : customers) {
if (customer.getText().equals("SQA")) {
WebElement test = customer;
System.out.println(test);
break;
}
}
print xpath: //div[#id='Customers']/table/tbody/tr and fail to actually include the specific index of the path? The above xpath is absolutely useless; I'm expecting the location of where SQA was found.
xpath: //div[#id='Customers']/table/tbody/tr[4]
I think it just prints the locator used to find the element. If you want the index, just change your code to
List<WebElement> customers = driver.findElements(By.xpath("//div[#id='Customers']/table/tbody/tr"));
for (int i = 0; i < customers.size(); i++)
{
if (customers.get(i).getText().equals("SQA"))
{
System.out.println(i);
break;
}
}

How to close a pop up window in Selenium?

I am trying to close a pop up window which is not allowing my code to execute further. But I am unable to do that. There is a a pop up window which says 'Free pound 5 voucher' which is not getting closed.
Below is my code. Please check and suggest.
public class Alldetails {
WebDriver driver;
public List<String> links1 = new ArrayList<String>();
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "C:\\Pankaj\\chromedriver.exe");
driver = new ChromeDriver();
// driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#Test
public void f() {
driver.get("http://www.debenhams.com/kids/t-shirts-tops/boys");
driver.findElement(
By.xpath(".//*[#id='dijit__WidgetsInTemplateMixin_0']/div/div[1]/button"))
.click();
WebElement a = driver.findElement(By.className("products_count"));
String product_count = a.getText();
Integer x = Integer.valueOf(product_count);
System.out.println(x);
for (int i = 1; i < (x / 60) + 1; i++) {
driver.get("http://www.debenhams.com/kids/t-shirts-tops/boys" + "?pn=" + i);
List<WebElement> links = driver
.findElements(By.className("item_container").tagName("a"));
for (WebElement abcx : links) {
String ax = abcx.getAttribute("href");
// if(!links1.contains(ax))
links1.add(ax);
}
for (String b : links1) {
if (b.contains("/webapp/wcs/stores/servlet/prod"))
System.out.println(b);
}
}
}
#AfterTest
public void afterTest() {
}
}
You need to do something like this:
Alert alert = driver.switchTo().alert();
// Prints text and closes alert
System.out.println(alert.getText());
alert.accept();
or
alert.dismiss();
according to your needs.
EDIT
You may get an AlertNotPresentException if your code runs before the alert appears. In order to avoid that you may add a delay like this:
WebDriverWait wait = new WebDriverWait(driver, 15, 100)
wait.until(ExpectedConditions.alertIsPresent())
This will make Selenium wait 15 seconds checking every 100 milliseconds if the alert appeared. This snippet is not mine and had been taken from here: Selenium how to get the alert Alert message

how to click a result from google search that is not on first page with selenium java

I am trying to navigate through search results from google with selenium webdriver. I have a interface for user to inset word to search and site title to choose. If the result is not on the first page the driver should go to next page to look for the site, and if not there than to next page and so on..
Somehow I don't manage to get beyond the second page end if I did get to the second page and the right site is there, the driver doesn't click on it.
Here is some of the code in Java:
private void setLoopNum(int l){
String getText = urlText.getText();
String getSiteName = linkToChoose.getText();
System.setProperty("webdriver.chrome.driver", "C:\\selenium-2.44.0\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); //Maximize window
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
for(int i=0;i<l;i++){
//WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
//driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
WebElement element1 = driver.findElement(By.name("q"));
element1.sendKeys(getText);
element1.submit();
//driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); //wait for page to load
//try{
boolean flag = false;
String page_number = "1";
while(! flag){
//get all the search results
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(WebElement eachResult: linkElements){
if(eachResult.getAttribute(getSiteName).equals(getSiteName)){
eachResult.findElement(By.xpath("//a[#href='" + getSiteName + "']")).click();;
flag =true;
}else{
driver.findElement(By.xpath("//a[#id='pnnext']/span")).click();
linkElements.clear(); //celean list
break;
} //end else
}
}//end while loop
//}catch(Exception e){
// System.out.println("Error!");
// }
}
driver.quit(); //clear memory
}
Three things that you are missing in your code:
Firstly, in your code you are looking for only first element in your list.
Secondly, in getAttribute you are passing link instead of href:
if(eachResult.getAttribute(getSiteName).equals(getSiteName)){
it should be:
if(eachResult.getAttribute("href").equals(getSiteName)){
Thirdly, on clicking next the page is loaded via Google Ajax Api. Thus webdriver click will never block the execution of your code and will load linkElements with previous page links only. To avoid this let the driver get refreshed or put some wait for certain condition in your code.
Can u try out with this code:
WebDriverWait wait = new WebDriverWait(driver, 10)
while (!flag) {
// get all the search results
linkElements = wait
.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='r']/a")));
for (WebElement eachResult : linkElements) {
if (eachResult.getAttribute("href").contains(getSiteName)) {
eachResult.click();
flag = true;
break;
}
}
if (!flag) {
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]"))
.click();
pageNumber++;
linkElements.clear(); // celean list
wait.until(ExpectedConditions
.textToBePresentInElementLocated(
By.xpath("//td[#class='cur']"), pageNumber
+ "")); // Checking whether page number is changed as expected.
}
}// end while loop
EDIT:
List<WebElement> linkElements = new ArrayList<WebElement>();
ListIterator<WebElement> itr = null;
System.setProperty("webdriver.chrome.driver",
"webdrivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); // Maximize window
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://google.com");
WebElement element1 = driver.findElement(By.name("q"));
WebElement toClick = null;
element1.sendKeys(getText);
element1.submit();
// try{
int pageNumber = 1;
WebDriverWait wait = new WebDriverWait(driver, 10);
boolean flag = false;
while (!flag) {
linkElements = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By
.xpath("//h3[#class='r']/a")));
itr = linkElements.listIterator(); // re-initializing iterator
while (itr.hasNext()) {
toClick = itr.next();
if (toClick.getAttribute("href").contains(getSiteName)) {
toClick.click();
flag = true;
break;
}
}
if (!flag) {
driver.findElement(By.xpath("//a[#id='pnnext']/span[1]"))
.click();
pageNumber++;
linkElements.clear(); // clean list
wait.until(ExpectedConditions.textToBePresentInElementLocated(
By.xpath("//td[#class='cur']"), pageNumber + ""));
}
}
driver.quit(); // clear memory
}
It looks like you're moving to the next page every time ANY of the WebElements in linkElements isn't what you're looking for. This will cause problems, as you need to relocate any elements that are re-rendered.
Give this a shot:
boolean found = false;
int page_number = 1; //If you need this as a string, you can make it one later
while(! found){
//get all the search results
List<WebElement> linkElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for(WebElement result: linkElements){
if(result.getAttribute("href").equals(getSiteName))
{
result.click();
found=true;
break;
}
}//End of foreach-loop
if(!found){
driver.findElement(By.xpath("//a[#id='pnnext']/span")).click();
page_number++;
}
}//End of while-loop
Also, you'll want to have some element-finding protection. Say that you search for something that has 0 results, or only one page of them (rare though that is). In the first case, you're lucky, because driver.findElements() should just return an empty list rather than throwing some exception, and the foreach loop just won't run, but in both cases, there won't be the anchor #pnnext, which will cause driver.findElement to throw an exception when you search for it. There are several ways to protect against this, such as writing a small wrapper function (IIRC, they have a simple implementation for findelementwithtimeoutwait() written on the Selenium website somewhere). I suggest you pick/write one and start using it, instead of the raw Selenium functions.

Selenium webdriver to select date

I am newbie to Selenium and not able to select date website http://www.redbus.in.
Can some one help me out? I tried to pass value to the read only text box, but it was in vain.
public static void setup() throws Exception {
System.out.println("Browser Set up start.. ");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.get("http://www.redbus.in/");
System.out.println("Browser Set up Completed ");
}
#Test
public static void SelectSrcDest() throws Exception {
System.out.println("Constructing Url to open");
driver.findElement(By.id("txtSource")).sendKeys("Bangalore");
driver.findElement(By.id("txtDestination")).sendKeys("Chennai");
driver.findElement(By.xpath("html/body/div[2]/div/section/div[1]/img")).click();
driver.findElement(By.xpath("html/body/div[2]/div/section/div[1]/img")).click();
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("window.document.getElementById('txtOnwardCalendar').setAttribute('value','27-Mar-2014')");
driver.findElement(By.xpath("html/body/div[2]/div/section/div[4]/button")).click();
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
setup();
SelectSrcDest();
}
You can use xPath to find the element by text and then use the div id & table class to choose which trip & month to pick.
For instance in order to select the date of journey:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.redbus.in");
driver.findElement(By.id("txtOnwardCalendar")).click();
By locator = By.xpath("//div[#id='rbcal_txtOnwardCalendar']" +
"/table[#class='monthTable first']" +
"//td[contains(text(), '10')]");
driver.findElement(locator).click();
would select the 10th day of the first month. If you use monthTable last as the class instead, you get 10th day of the second month. And if you change the div id into rbcal_txtReturnCalendar, you can pick a date for the return trip.
You can try the following piece of code. It works perfect
driver.findElement(By.id("DDLSource")).sendKeys("C");
driver.findElement(By.xpath("//dl[#id = 'lis']//dt[text()='Chennai']")).click();
driver.findElement(By.id("DDLDestination")).sendKeys("t");
driver.findElement(By.xpath("//dl[#id = 'dis']//dt[text()='Theni']")).click();
driver.findElement(By.className("calenImg")).click();
driver.findElement(By.xpath("//td[text()='Feb']/../..//a[text()='17']")).click();
driver.findElement(By.id("calendar1")).click();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.xpath("//td[text()='Feb']/../..//a[text()='20']")).click();
Try this to select the date:
driver.findElement(By.id("give id")).click();
WebElement selectElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.className("ui-datepicker-year")));
Select select = new Select(selectElement);
select.selectByValue("2012");
Thread.sleep(6000);
WebElement dateWidget = driver.findElement(By.id("ui-monthpicker-div"));
List<WebElement> columns011=dateWidget011.findElements(By.tagName("td"));
for (WebElement cell: columns011){
//Select Month
if (cell.getText().equals("Feb")){
cell.findElement(By.linkText("Feb")).click();
break;
}
}
Try to figure out the element through ID.. Its very easy to target exactly by the ID.
driver.findElement(By.id("txtOnwardCalendar")).click();
WebElement selectElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.className("monthTable first")));
Select select = new Select(selectElement);
select.selectByValue("2012");
Thread.sleep(6000);
WebElement dateWidget = driver.findElement(By.id("monthTitle"));
List<WebElement> columns011=dateWidget011.findElements(By.tagName("td"));
for (WebElement cell: columns011){
//Select Month
if (cell.getText().equals("Feb")){
cell.findElement(By.linkText("Feb")).click();
break;
}
}

Categories

Resources