I am new to selenium and I am trying to verify selected date in datepicker field but when I am executing this program it is printing else section, which it should not show. Kindly help to know where I am going wrong.
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class tripadviser {
static WebDriver driver;
public static void main(String[] args) {
String start_date = "29-March 2017";
String[] splitter = start_date.split("-");
String start_day = splitter[0];
String start_month = splitter[1];
System.setProperty("webdriver.chrome.driver", "D:\\rakesh\\software\\selenium browser\\New folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.tripadvisor.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.id("rdoFlights")).click();
WebElement datepicker_ele = driver.findElement(By.id("metaCheckInSpan"));
datepicker_ele.click();
select_date_fun(start_day, start_month);
WebElement check_in_ele = driver.findElement(By.id("checkIn"));
String datepicker_expected_str = "29/3/2017";
if (check_in_ele.getText().equals(datepicker_expected_str)) {
System.out.println("Date selection is done succesfully");
} else {
System.out.println("Something went wrong");
}
driver.close();
}
public static void select_date_fun(String day, String month_year) {
List < WebElement > month_ele = driver.findElements(By.xpath(".//div[#class='calendar']/div[#class='month']/table/thead/tr/th[#class='caption']"));
for (int i = 0; i < month_ele.size(); i++) {
//System.out.println(month_ele.get(i).getText());
if (month_ele.get(i).getText().equals(month_year)) {
List < WebElement > day_ele = driver.findElements(By.xpath(".//div[#class='calendar']/div[#class='month'][1]/table/tbody/tr/td/a"));
for (WebElement j: day_ele) {
//System.out.println(j.getText());
if (j.getText().equals(day)) {
j.click();
return;
}
}
}
}
}
}
My question is resolved by using .getAttribute("value") instead of .getText()
Related
I want to get the background color of an element which is scrolling.
https://www.ndtv.com/business in this website, i want to get the background color of GOLD whether its red or Blue...
Sometime i can find the element , like, when its available in the web..other times it returned as element not found...
How can i make sure, i will get it for sure..
Here is the code..I used wait, and Javascript..both return the same error...
[![import org.testng.annotations.Test;
import junit.framework.Assert;
import org.testng.annotations.BeforeTest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
public class Question3 {
WebDriver driver ;
WebDriverWait wait;
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", Arrays.asList("disable-popup-blocking"));
options.addArguments("--disable-popup-blocking");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://www.ndtv.com/business ");
System.out.println("******* Execution Started **********");
}
#Test
public void test() throws InterruptedException {
driver.switchTo().frame(1);
JavascriptExecutor js = (JavascriptExecutor)driver;
wait = new WebDriverWait(driver,90);
Actions action = new Actions(driver);
String filename = "src\\test\\resources\\screenshots\\Question3.png";
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*\[#id=\"header-data\"\]/a\[6\]/span/span\[1\]")));
try {
String Gold_old = driver.findElement(By.xpath("//*\[#id=\"header-data\"\]/a\[6\]/span/span\[1\]")).getAttribute("innerText");
System.out.println("Gold old : "+ Gold_old);
String Gold_new = driver.findElement(By.xpath("//*\[#id=\"header-data\"\]/a\[6\]/span/span\[2\]/span")).getAttribute("innerText");
System.out.println("Gold New : "+ Gold_new);
String Variation = driver.findElement(By.xpath("//*\[#id=\"header-data\"\]/a\[6\]/span/span\[2\]")).getAttribute("innerText");
String Var_Value = Variation.substring(8, 14);
System.out.println("Gold variation : "+ Var_Value);
}catch(Exception e) {
System.out.println("Running from Exception..." + e.getMessage());
String Gold_old = driver.findElement(By.xpath("//*\[#id=\"header-data\"\]/a\[6\]/span/span\[1\]")).getAttribute("innerText");
System.out.println("Gold old : "+ Gold_old);
String Gold_new = driver.findElement(By.xpath("//*\[#id=\"header-data\"\]/a\[6\]/span/span\[2\]/span")).getAttribute("innerText");
System.out.println("Gold New : "+ Gold_new);
String Variation = driver.findElement(By.xpath("//*\[#id=\"header-data\"\]/a\[6\]/span/span\[2\]")).getAttribute("innerText");
String Var_Value = Variation.substring(8, 14);
System.out.println("Gold variation : "+ Var_Value);
}
//wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//*\[#id=\"header-data\"\]/a\[8\]/span/span\[2\]")));
String sText = js.executeScript("return document.driver.findElement(By.xpath(\"//*\[#id=\"header-data\"\]/a\[8\]/span/span\[2\]\")).style.background-color;").toString();
System.out.println(sText);
String Background = driver.findElement(By.xpath("(//*\[#id=\"header-data\"\]/a\[8\]/span/span\[2\]")).getCssValue("background-color");
System.out.println("Background color is : "+ Background);
String BG_RGB = Background.replace("rgba(", "rgb(");
String RGB = BG_RGB.substring(0, 14) + ")" ;
String RGB_Value = RGB.substring(3);
System.out.println("Background color in RGB is : "+ RGB );
System.out.println(" RGB value is : "+ RGB_Value);
Assert.assertEquals("(12, 162, 2)", RGB_Value);
Thread.sleep(1000);
wait.until(ExpectedConditions.stalenessOf(driver.findElement(By.xpath("/html/body/div/header/header/div/div\[1\]/div\[2\]/div/div/div/div/a\[4\]"))));
//driver.findElement(By.xpath("/html/body/div/header/header/div/div\[1\]/div\[2\]/div/div/div/div/a\[4\]")).click();
js.executeScript("argument\[0\].click();",driver.findElement(By.xpath("/html/body/div/header/header/div/div\[1\]/div\[2\]/div/div/div/div/a\[4\]")) );
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a\[#id=\"By Gain\"\]"))));
action.moveToElement(driver.findElement(By.xpath("//a\[#id=\"By Gain\"\]"))).perform();
js.executeScript("argument\[0\].click();",driver.findElement(By.xpath("//a\[#id=\"By Gain\"\]")));
Thread.sleep(1000);
System.out.println("********** Clicked Gain *********");
//JavascriptExecutor js = (JavascriptExecutor) driver;
//js.executeScript("arguments\[0\].scrollIntoView();", driver.findElement(By.xpath("//a\[#id=\"By Gain\"\]")));
//js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
Thread.sleep(1000);
WebElement firstchoice = driver.findElement(By.xpath("//*\[#id=\"peerlist1\"\]/li\[1\]"));
action.moveToElement(firstchoice).perform();
utils.HelperFunctions.captureScreenShot(driver, filename);
Thread.sleep(1000);
String cellvalue = driver.findElement(By.xpath("//*\[#id=\"peerlist1\"\]/li\[1\]/a/span")).getText();
System.out.println("Hover Text is " + cellvalue);
String CellRGB = driver.findElement(By.xpath("//*\[#id=\"peerlist1\"\]/li\[1\]")).getCssValue("background-color");
System.out.println("Cell's RGB value is " + CellRGB);
try {
String celltext = driver.findElement(By.xpath("//*\[#id=\"peerlist1\"\]/li\[1\]/a")).getAttribute("innerText");
System.out.println("Cell's text is " + celltext);
}catch(Exception e) {
String celltext = driver.findElement(By.xpath("//*\[#id=\"peerlist1\"\]/li\[1\]/a")).getText();
System.out.println("Cell's text is " + celltext);
}
List<WebElement> row_data = driver.findElements(By.xpath("//*\[#id=\"peerlist1\"\]/li\[*\]"));
int i = 0;
ArrayList<String> obtainedList = new ArrayList<>();
for(WebElement li : row_data) {
if(i>=6) {
break;
}else {
String text = li.getText();
obtainedList.add(text);
i++;
}
}
System.out.println("Original List " + obtainedList);
ArrayList<String> sortedList = new ArrayList<>();
for(String s:obtainedList){
sortedList.add(s);
}
Collections.sort(sortedList);
System.out.println("Sorted List " + sortedList);
Assert.assertTrue(sortedList.equals(obtainedList));
}
#AfterTest
public void afterTest() {
System.out.println("******* Execution end **********");
driver.quit();
}
}][1]][1]
The only issue i can see with your code is that you have written a lot of messed xpaths. You have used escape character (\) unnecessary, which has make your xPath very difficult to analyse. I have taken one of the block to demonstrate. You can use same for all elements.
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver,60);
driver.manage().window().maximize();
driver.get("https://www.ndtv.com/business");
driver.switchTo().frame(1);
WebElement ele = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id='header-data']/a[8]/span/span[2]")));
String Background = ele.getCssValue("background-color");
System.out.println("RGB : "+ Background);
//In case you want hex value of color code
String hex = Color.fromString(Background).asHex();
System.out.println(hex);
output:
Note : Also do not use combination of both implicit wait and explicit wait in your script. It will make your script unpredictable and can cause long delays even when not needed.
Getting error at this method
gettablevalueshopcart("//div[#id='Catalog']//tr",2,"Large Angelfish",0,"EST-1");
Browser launching
public class petstore {
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\achelimi\\Downloads\\chromedriver_win32 (1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("https://jpetstore.cfapps.io/catalog");
driver.findElement(By.xpath("//a[contains(text(),'Sign In')]")).click();
driver.findElement(By.name("username")).sendKeys("Testing15");
driver.findElement(By.name("password")).sendKeys("test#123");
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath("//div[#id='SidebarContent']/a[contains(#href,'FISH')]/img")).click();
driver.findElement(By.xpath("//td[contains(text(),'Angelfish')]//preceding-sibling::td//a")).click();
gettablevalueshopcart("//div[#id='Catalog']//tr",2,"Large Angelfish",0,"EST-1");
// gettablevalueshopcart("//div[#id='Catalog']//tr",2,"",0,"");
driver.quit();
}
created below method
public static void gettablevalueshopcart(String xPath1,int descriptionid, String expectvalue1, int itemid, String expectedvalue2) {
Used try and catch ,able to see output as null
try
{
//String xPath1 = "//div[#id='Catalog']//tr";
List<WebElement> shoppingtableList = driver.findElements(By.xpath(xPath1));
System.out.println("Item ID\t\tProduct ID\t\tDescription\t\tInstock\t\tList Price\tTotalcost\t\tButton");
System.out.println("---------------------------------------------------------------------------------------------------------------------------------");
for(int i=1;i<shoppingtableList.size();i++) {
List<WebElement> listData = driver.findElements(By.xpath(xPath1+"["+(i+1)+"]/td"));
for(int j=0;j<listData.size();j++) {
System.out.print(listData.get(j).getText()+"\t\t");
}
System.out.println();
}
// description is in the 3rd(2nd index) column so we can fetch that with the index number 2.
for(int i=1;i<shoppingtableList.size();i++) {
List<WebElement> listData = driver.findElements(By.xpath(xPath1+"["+(i+1)+"]/td"));
Compared expected output with actual value
if(listData.get(descriptionid).getText().trim().equals(expectvalue1))
{
System.out.println("Description for Item ID is "+listData.get(descriptionid).getText());
}
Compared expected output with actual value
if(listData.get(itemid).getText().trim().equals(expectedvalue2)) {
System.out.println("Item ID is "+listData.get(itemid).getText());
break;
}
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
This is the entire code.Copy and paste it.I have declared WebDriver globally.
package SeleniumPractice;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import org.openqa.selenium.WebElement;
public class TestS_1 {
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\achelimi\\Downloads\\chromedriver_win32 (1)\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("https://jpetstore.cfapps.io/catalog");
driver.findElement(By.xpath("//a[contains(text(),'Sign In')]")).click();
driver.findElement(By.name("username")).sendKeys("Testing15");
driver.findElement(By.name("password")).sendKeys("test#123");
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath("//div[#id='SidebarContent']/a[contains(#href,'FISH')]/img")).click();
driver.findElement(By.xpath("//td[contains(text(),'Angelfish')]//preceding-sibling::td//a")).click();
gettablevalueshopcart("//div[#id='Catalog']//tr",2,"Large Angelfish",0,"EST-1");
driver.quit();
}
public static void gettablevalueshopcart(String xPath1,int descriptionid, String expectvalue1, int itemid, String expectedvalue2)
{
try
{
//String xPath1 = "//div[#id='Catalog']//tr";
List<WebElement> shoppingtableList = driver.findElements(By.xpath(xPath1));
System.out.println("Item ID\t\tProduct ID\t\tDescription\t\tInstock\t\tList Price\tTotalcost\t\tButton");
System.out.println("---------------------------------------------------------------------------------------------------------------------------------");
for(int i=1;i<shoppingtableList.size();i++) {
List<WebElement> listData = driver.findElements(By.xpath(xPath1+"["+(i+1)+"]/td"));
for(int j=0;j<listData.size();j++) {
System.out.print(listData.get(j).getText()+"\t\t");
}
System.out.println();
}
// description is in the 3rd(2nd index) column so we can fetch that with the index number 2.
for(int i=1;i<shoppingtableList.size();i++) {
List<WebElement> listData = driver.findElements(By.xpath(xPath1+"["+(i+1)+"]/td"));
if((listData.get(descriptionid).getText()).trim().equals(expectvalue1))
{
System.out.println("Description for Item ID is "+listData.get(descriptionid).getText());
}
if(listData.get(itemid).getText().trim().equals(expectedvalue2)) {
System.out.println("Item ID is "+listData.get(itemid).getText());
break;
}
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Here is the output:
Item ID Product ID Description Instock List Price Totalcost Button
---------------------------------------------------------------------------------------------------------------------------------
EST-1 FI-SW-01 Large Angelfish $16.50 Add to Cart
EST-2 FI-SW-01 Small Angelfish $16.50 Add to Cart
Description for Item ID is Large Angelfish
Item ID is EST-1
I apologize if this is a stupid question.But why can I only extract one list to an excel? I've tried modifying it but I don't really understand why I can't have 2 columns side by side with the extracted data. Instead it displays one.
Any fixes?
I have following code :
public class dads
{
public static void main(String args[]) throws Exception
{
SXSSFWorkbook workbook = new SXSSFWorkbook(100);
SXSSFSheet sheet = workbook.createSheet("output");
FileOutputStream f = new FileOutputStream("czPA LEASE.xlsx",true);
// DRIVER
WebDriver driver=new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/List_of_Death_Note_episodes");
List<WebElement> Elements=driver.findElements(By.xpath("//table//tbody//td//i"));
int x=-1;
int y=1;
for(WebElement ele: Elements)
{
System.out.println(ele.getText());
SXSSFRow dataRow = sheet.createRow((short)++x);
SXSSFCell cell=dataRow.createCell(0);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(ele.getText());
}
List<WebElement> Elements1=driver.findElements(By.xpath("//table//tbody//td"));
int x1=-1;
int y1=2;
for(WebElement ele1: Elements1)
{
System.out.println(ele1.getText());
SXSSFRow dataRow = sheet.createRow((short)++x1);
SXSSFCell cell1=dataRow.createCell(1);
cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
cell1.setCellValue(ele1.getText());
}
try
{
f.flush();
workbook.write(f);
f.close();
System.out.println("Excel written successfully..");
driver.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I hope this will help you to find you answer:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class Test {
static WebDriver driver = new FirefoxDriver();
static WebElement element ;
public static void main(String[] args) throws InterruptedException, IOException {
String excelFileName = "C:/Test.xls";//name of excel file
String sheetName = "Sheet1";//name of sheet
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName) ;
// DRIVER
WebDriver driver=new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/List_of_Death_Note_episodes");
List<WebElement> rows=driver.findElements(By.xpath(".//table[#class='wikitable'][1]//th[contains(#id,'ep')]"));
//iterating r number of rows
for (int r=0;r < rows.size(); r++ )
{
HSSFRow row = sheet.createRow(r);
List<WebElement> cloumns = driver.findElements(By.xpath(".//table[#class='wikitable'][1]//th[#id='ep"+r+"']//parent::tr[1]/td"));
//iterating c number of columns
for (int c=0;c < cloumns.size(); c++ )
{
HSSFCell cell = row.createCell(c);
cell.setCellValue(cloumns.get(c).getText());
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
}
My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.
It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.
Code is :
public class EcommerceSearchResult {
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow
= driver.findElements
(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count);
for(int i = 0 ; i<count ; i++)
{
List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
System.out.println(gridrow.get(i).getText());
listingelementinloop.get(i).click();
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}
}
In the loop you need to replace following line:
System.out.println(gridrow.get(i).getText());
With
System.out.println(listingelementinloop.get(i).getText());
As, elements in the gridrow list will become stale once you click on 'Back' button of browser.
Alternatively, following is another way of performing the same task:
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow
= driver.findElements
(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count);
for(int i = 1 ; i<=count ; i++)
{
WebElement element =
driver.findElement(By.xpath(".//*[#id='grid_view_products_page_container']/div/div[" + i + "]"));
System.out.println(element.getText());
element.click();
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}
}
Let me know, if you have any further queries.
The problem is that you are looping through a collection of elements that you collected from the page. Once you leave that page or reload it, the element references you were storing become stale, thus the error. One way to get around this is to use an index into the collection and loop over that. I've rewritten your code to make use of functions to take care of repeated actions. I've tested this code and it works.
Part of main
driver.get("http://store.demoqa.com/");
Search("iphone");
for (int i = 0; i < GetProductCount(); i++)
{
ClickProduct(i);
driver.navigate().back();
}
and supporting functions
public void Search(String searchTerm)
{
driver.findElement(By.cssSelector("input[value='Search Products']")).sendKeys(searchTerm + "\n");
}
public void ClickProduct(int index)
{
driver.findElements(By.cssSelector("h2 > a")).get(index).click();
}
public int GetProductCount()
{
return driver.findElements(By.cssSelector("h2 > a")).size();
}
Below is the solution code for your problem.Tested it in my machine and attached console screenshot.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class EcommerceSearchResult {
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow = driver.findElements(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count+"\n");
for(int i = 0 ; i<count ; i++)
{
WebElement listingelementinloop = driver.findElement(By.xpath(".//*[#id='grid_view_products_page_container']/div/div["+(i+1)+"]"));
System.out.println(listingelementinloop.getText());
listingelementinloop.findElement(By.xpath(".//div/a")).click();
wait.until(ExpectedConditions.urlContains("products-page/product-category"));
driver.navigate().back();
wait.until(ExpectedConditions.titleIs("iphone | Search Results | ONLINE STORE"));
}
}
}
I am trying to print names of all result links on the first 5 pages on Google.com
Scenario is,
1) Go to www.google.com and search for something.
2) Print names of all result links on first 5 pages
I am able to print all the result links of first page and click next page link. But second page links are not printing. I think the reason may be with the xpath changing in second page. If so, how do I print all the links of 2nd 3rd 4th and 5th page.
Kindly help me in solving this solution.
package com;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class Exercise2 {
static WebDriver d;
public static void main(String[] args) throws InterruptedException {
ProfilesIni prop = new ProfilesIni();
FirefoxProfile seleniumProfile = prop.getProfile(("Selenium"));
d = new FirefoxDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
d.get("http://www.google.com");
Thread.sleep(5000);
d.findElement(By.name("q")).sendKeys("Selenium");
d.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
//Print names of all result links on first page.
String part1 = "//div[#id='rso']/div[2]/div[";
String part2 = "]/div/h3/a";
for(int i=2;i<=5;i++){
String part3 = "//div[#id='navcnt']/table/tbody/tr/td[";
String part4 = "]";
int a = 1;
while(isElementPresent(part1+a+part2)){
String text = d.findElement(By.xpath(part1+a+part2)).getText();
System.out.println(text);
a++;
}
Thread.sleep(5000);
System.out.println("*************Next Page**********");
Thread.sleep(5000);
d.findElement(By.xpath(part3+i+part4)).click();
}
}
public static boolean isElementPresent(String xpathexp){
List<WebElement> allList = d.findElements(By.xpath(xpathexp));
//WebElement nextPages = d.findElement(By.xpath(nextPage1));
if(allList.size()==0)
{
return false;
}else{
return true;
}
}
}
List<WebElements> links = driver.findElements(By.tagName("a"));
for(int i = 0 ; i < 5 ; i ++)
{
string firstLink = links[i].getAttribute("href");
}
try following code.
package javaselenium;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
*
* #author Muhammad USman
*/
public class JavaSelenium {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Hello Wrold");
GetUrls("Selenium");
}
public static ArrayList GetUrls(String keyWord)
{
FirefoxDriver driver;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("https://www.google.com/?gws_rd=ssl");
WebElement qElement;
qElement = driver.findElement(By.name("q"));
qElement.sendKeys(keyWord);
qElement.sendKeys(Keys.ENTER);
try {
Thread.sleep(3*1000);
} catch (InterruptedException ex) {
Logger.getLogger(JavaSelenium.class.getName()).log(Level.SEVERE, null, ex);
}
//give number how mange pages you want to crawl
int nPageToCrawl=5;
List links;
links=new ArrayList();
for (int i = 0; i < nPageToCrawl; i++) {
if(i>0)
{
System.out.println("***Click on Next Page***");
//Click on Next Page
driver.findElement(By.id("pnnext")).click();
try {
Thread.sleep(3*1000);
} catch (InterruptedException ex) {
Logger.getLogger(JavaSelenium.class.getName()).log(Level.SEVERE, null, ex);
}
}
//it will get all links of pageLinks
List<WebElement> pageLinks = driver.findElements(By.cssSelector(".r>a"));
for (WebElement pageLink : pageLinks) {
links.add(pageLink.getAttribute("href"));
System.out.println(pageLink.getText());
System.out.println(pageLink.getAttribute("href"));
}
}
//close browser
driver.quit();
return (ArrayList) links;
}
}
if any issue then let me know.