I need to get all the links in a web page and store it in first column in excel sheet and check whether the link is broken are valid and update the result in second column in same excel sheet.
Here is the code I have tried,
public class login {
public WebDriver driver;
#BeforeTest
public void login1() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "driver path");
driver.get("url");
Thread.sleep(20000);
}
#Test
public void data() throws IOException {
File src = new File("excel path");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet Sheet1 = wb.getSheetAt(0);
Sheet1.createRow(0).createCell(0);
List<WebElement> links=driver.findElements(By.tagName("a"));
String url = "";
HttpURLConnection huc;
int respCode = 200;
int cell =0;
for(int i=0;i<links.size();i++) {
WebElement alinks = links.get(i);
String allinks = alinks.getAttribute("href");
System.out.println(allinks);
XSSFRow row = Sheet1.createRow(i);
XSSFCell excelCell = row.createCell(cell);
excelCell.setCellValue(allinks);
}
Iterator<WebElement> it = links.iterator();
while(it.hasNext()){
url = it.next().getAttribute("href");
System.out.println(url);
if(url == null || url.isEmpty()){
System.out.println("URL is not yet published");
continue;
}
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
for (int i=1; i <= Sheet1.getLastRowNum(); i++){
Cell resultCell= Sheet1.getRow(i).getCell(1);
if(respCode >= 400){
System.out.println(url+" is a broken link");
resultCell.setCellValue("FAIL");
}
else{
System.out.println(url+" is a valid link");
resultCell.setCellValue("PASS");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fout = new FileOutputStream(src);
wb.write(fout);
}
With this code I can able to get all the links from the web page and store it in first column of excel sheet but when checking for broken links only the first link is checked and before checking second link it throws java.lang.NullPointerException error at this line resultCell.setCellValue("PASS"); Can any one help on this?
In the above case, the cell does not exist yet, so getCell returns null.
You must detect this and create the cell if it doesn't exist, with createCell method:
Cell resultCell= Sheet1.getRow(i).getCell(1);
if (cell == null)
{
cell = Sheet1.getRow(i).createCell(1);
}
// Then set the value.
cell.setCellValue("PASS");
Alternatively, there is an overload of getCell where you can specify a MissingCellPolicy so that a blank Cell is automatically created if it didn't already exist:
cell = sheet.getRow(i).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Here is my code
public class MyClass
{
public void readExcel(String filePath,String fileName,String sheetName) throws IOException{
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// To Maximize browser screen
driver.manage().window().maximize();
//Test 5 : Excel Read
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
String fileExtensionName = fileName.substring(fileName.indexOf("."));
Workbook guru99Workbook = null;
if(fileExtensionName.equals(".xlsx")) {
guru99Workbook = new XSSFWorkbook(inputStream);
}
else if(fileExtensionName.equals(".xls")){
guru99Workbook = new HSSFWorkbook(inputStream);
}
Sheet guru99Sheet = guru99Workbook.getSheet(sheetName);
//Find number of rows in excel file
int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();
for (int i = 0; i < rowCount+1; i++) {
Row row = guru99Sheet.getRow(i);
//Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++) {
//Print Excel data in console
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
}
}
}
//Main function is calling readExcel function to read data from excel file
public static void main(String...strings) throws IOException{
//Create an object of ReadGuru99ExcelFile class
MyClass objExcelFile = new MyClass();
//Prepare the path of excel file
String filePath = System.getProperty("user.dir")+"\\src\\newpackage";
//excelExportAndFileIO
//Call read file method of the class to read data
objExcelFile.readExcel(filePath,"Keywords.xlsx","ExcelGuru99Demo");
}
}
Here is the error :
Exception in thread "main" java.lang.NoSuchFieldError:
RAW_XML_FILE_HEADER at
org.apache.poi.poifs.filesystem.FileMagic.(FileMagic.java:42)
at
org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:208)
at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:98)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:324)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37) at
org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:295)
at newpackage.MyClass.readExcel(MyClass.java:139) at
newpackage.MyClass.main(MyClass.java:184)
PS : I am new to Selenium so learning this feature from :
https://www.guru99.com/all-about-excel-in-selenium-poi-jxl.html
Please help me , TIA
Hi I googled for it & found solution of my error :
I had to include one more jar.
xmlbeans-2.3.0.jar
Such error or suggestion was not giving though while creating / building code, I wonder why not..
I m sending the firepath screenshot
I want to select first element and display in element text box
Can someone please help in this
You can update your code as below:
public class SelectAutoSugggestedValue {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.google.com");
driver.findElement(By.id("gbqfq")).sendKeys("automation tutorial");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List allOptions = driver.findElements(By.xpath("//td/span[text()='automationtutorial']"));
for (int i = 0; i < allOptions.size(); i++) {
String option = allOptions.get(i).getText();
System.out.println(option);
}
}
}
I am working on Java-selenium test framework.
We are calling individual page objects for testing methods viz:
verifyOrderSummary()
These methods sitting inside Page Object will have individual TestNG asserts
Now, when I run my main calling methods / TestNG Tests then, after execution of the test result of the assert is not getting written in the TestNG report.
Kindly advise.
How should I structure my Page Object driven tests, so that- assertings (soft/hard) will get reflected in the final TestNG report.
Many thanks
Hi, Below is one of the key test method( calling various page objects representing various pages):
#Test(dataProvider="BillingDataExcel")
public void dataEntryMethod(String sNo, String sTestCaseName, String sTestDesc, String sAddMedia, String sSupplyVia, String sClock, String sAdvertiser, String sSubtitles, String sBrand, String sPriceModel, String sMarket) throws InterruptedException, IOException {
try{
loginToA5();
navigateToDeliveryDashboard();
softAssert = new SoftAssert();
deliveryLandingPageDataVariant = new DeliveryLandingPageDataVariant(driver);
Thread.sleep(1000);
deliveryLandingPageDataVariant.triggerCreateOrder();
Thread.sleep(1000);
deliveryLandingPageDataVariant.changeCountry(sMarket);
Thread.sleep(1000);
deliveryLandingPageDataVariant.addMedia(sAddMedia, sSupplyVia);
//****XML Driven variant below****
//deliveryLandingPageDataVariant.AddInformation();
deliveryLandingPageDataVariant.AddInformation(sClock,sAdvertiser,sSubtitles,sBrand);
//****XML Driven variant below****
//deliveryLandingPageDataVariant.selectBroadCastDest();
deliveryLandingPageDataVariant.selectBroadCastDest(sNo);
myUtil.TakeSnapShot(driver, "AfterFilling-inData");
deliveryLandingPageDataVariant.submitData();
Thread.sleep(2000);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
ViewOrderPage viewOrderPage = new ViewOrderPage(driver);
softAssert.assertTrue(viewOrderPage.verifyOrderSummary(sNo,sTestCaseName,myUtil.excelFeederRowCount++));
viewOrderPage.openOrderSummaryAndVerifyDesti(sNo);
/*Below is a Temp hook, before we fix the #After annotation */
driver.close();
driver.quit();
Thread.sleep(1000);
}catch(AssertionError e){
System.out.println("Assertion error or other error -- ");
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
And below is the One of Page Object:
public class ViewOrderPage extends Abstractpage {
XMLDataReader xmlDataReader = new XMLDataReader();
#FindBy(css="#angularHolder > div > div > div.clearfix.pbxs.ng-scope > div > div:nth-child(2) > div > div > div:nth-child(2)")
//#FindBy(xpath=".//*[#id='angularHolder']/div/div/div[1]/div/div[2]/div/div/div[2]")
private WebElement QTYValue;
#FindBy(xpath=".//*[#id='angularHolder']/div/div/div[1]/div/div[3]/div/div[1]/div[2]/span")
private WebElement subTotalValue;
#FindBy(xpath="//button[#data-role='viewReport']")
private WebElement viewOrderSummaryButton;
private final String WAIT_WHEEL_PATH =".//*[#id='angularHolder']/div/div/div[2]/div[2]";
private int i;
String STDCell;
String EXPCell;
String STACell;
private final String DELIVER_TO_STRING=".//*[#id='report']/div/div[2]/div[4]/table/tbody/tr";
public ViewOrderPage(WebDriver driver){
this.driver=driver;
AjaxElementLocatorFactory aFactory= new AjaxElementLocatorFactory(driver, 20);
PageFactory.initElements(aFactory, this);
myWait=new WebDriverWait(driver, 120);
myWait.until(ExpectedConditions.elementToBeClickable(viewOrderSummaryButton));
//myWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(WAIT_WHEEL_PATH));
}
#SuppressWarnings("finally")
public boolean verifyOrderSummary(String sNo, String sTestCaseName, int feederRowCount) throws Exception{
int subTotal=-1;
int qty=-1;
boolean valueMatched = false;
System.out.println("\n=========================Verify Order Summary Section=================================");
System.out.println("**Quantity =" + getQTY());
System.out.println("**subTotal ="+ getSubTotal());
try {
ExcelUtils.setExcelFile(System.getProperty("user.dir")+"/src/test/java/com/SAPAutomation/testData/BillingData.xlsx","TestResults");
ExcelUtils.setCellData(sNo, feederRowCount, 0);
ExcelUtils.setCellData(sTestCaseName, feederRowCount, 1);
ExcelUtils.setCellData(getQTY(), feederRowCount, 2);
ExcelUtils.setCellData(getSubTotal(), feederRowCount, 3);
System.out.println("Test Results Read: "+ (String.valueOf(ExcelUtils.getCellData(feederRowCount, 4)).toLowerCase()));
if(getSubTotal().toLowerCase().equals("£"+String.valueOf(ExcelUtils.getCellData(feederRowCount, 4)).toLowerCase()+".00")){
valueMatched=true;
System.out.println("\n**Subtotle of "+feederRowCount+" Matched**");
ExcelUtils.setCellData("PASS", feederRowCount, 5);
}else{
ExcelUtils.setCellData("FAIL", feederRowCount, 5);
System.out.println("\n**Subtotle of "+feederRowCount+" didn't match**");
valueMatched=false;
}//end else
// try {
// Assert.assertEquals(getSubTotal(), String.valueOf(ExcelUtils.getCellData(feederRowCount, 4)), "Quantity Matched");
// } catch (Exception e) {
// e.getMessage();
//
// Reporter.log("Assertion error in Verify Order summary:"+ e.getMessage());
// }
} catch (Exception e1) {
e1.printStackTrace();
}finally{
myUtil.takeFieldSnapshot(driver, driver.findElement(By.xpath(".//*[#id='angularHolder']/div/div/div[1]/div")), "OrderSummaryHighlight");
return valueMatched;
}
}
#SuppressWarnings("finally")
private String getQTY(){
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
String QTY = "0";
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try{
return QTY=QTYValue.getText();
}catch(Exception e){
e.getStackTrace();
return QTY;
}
}
private String getSubTotal(){
String subTotal="";
try{
return subTotal = subTotalValue.getText();
}catch (Exception e){
e.getStackTrace();
return subTotal;
}
}
public void openOrderSummaryAndVerifyDesti(String sNo) throws Exception{
String mainWinHande=driver.getWindowHandle();
viewOrderSummaryButton.click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Set<String> handles = driver.getWindowHandles();
for(String handle : handles)
{
if(!mainWinHande.equals(handle))
{
driver.switchTo().window(handle);
String attriAndDestinations[][]=ExcelUtils.getTableArray(System.getProperty("user.dir")+"/src/test/java/com/SAPAutomation/testData/BillingData.xlsx", sNo, myUtil.GLOBAL_MAX_COLUMN_COUNT);
ExcelUtils.setExcelFile(System.getProperty("user.dir")+"/src/test/java/com/SAPAutomation/testData/BillingData.xlsx",sNo);
String destinationCell="";
STDCell="--";
EXPCell="--";
STACell="--";
int broadcasterTableSize= driver.findElements(By.xpath(DELIVER_TO_STRING)).size();
for(i=1;i</*broadcasterTableSize*/attriAndDestinations.length+1;i++){
int xPathDIVCounter=i+2;
//Get Destination
destinationCell=driver.findElement(By.xpath(DELIVER_TO_STRING+"["+xPathDIVCounter+"]/td[2]")).getText();
ExcelUtils.setCellData(destinationCell, i, 3);
System.out.println("\n**DEBUG: Destination Cell value ="+destinationCell);
//Get Attribute
//--STD
STDCell=driver.findElement(By.xpath(DELIVER_TO_STRING+"["+xPathDIVCounter+"]/th[1]")).getText();
ExcelUtils.setCellData(STDCell, i, 4);
System.out.println("\n**DEBUG: STD Cell value ="+STDCell);
//Get Attribute
//--EXP
EXPCell=driver.findElement(By.xpath(DELIVER_TO_STRING+"["+xPathDIVCounter+"]/th[2]")).getText();
ExcelUtils.setCellData(EXPCell, i, 5);
System.out.println("\n**DEBUG: EXP Cell value ="+EXPCell);
//Get Attribute
//--STA ** SPECIAL CASE** TO DO
// EXPCell=driver.findElement(By.xpath(DELIVER_TO_STRING+"["+xPathCounter+"]/th[3]")).getText();
// ExcelUtils.setCellData(STDCell, i, 6);
}//end for
// tallyTableRowsWithNumberOfDestinations(attriAndDestinations.length);
}//end if
}//end for
driver.close(); // close the poped-up report window
driver.switchTo().window(mainWinHande);
}
private void tallyTableRowsWithNumberOfDestinations(int destinationSize){
int rowCount= driver.findElements(By.xpath(DELIVER_TO_STRING)).size();
System.out.println("\n** Table row Count: "+rowCount +"| destinations ArraySize: "+destinationSize);
try {
softAssert.assertEquals(rowCount-1, destinationSize+1, "Table rowcount didn't match with the Number of destinations selected");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void concludeAsserts(){
softAssert.assertAll();
}
}
As mentioned in the comments, you should separate your test logic out of your page objects. The page objects should report or alter the current state of the page, and it's up to the tests to decide whether what the page object reports is correct.
Break your page object method up more so that each one sets or checks one item on the page, then check each of those items from your test...
Assert.AreEqual(thePage.getOrderTotal(), expectedValue1);
Assert.AreEqual(thePage.getOrderItem(1), expectedValue2);
Assert.AreEqual(thePage.getOrderItem(2), expectedValue3);
Assert.AreEqual(thePage.getAnotherThing(), expectedValue4;
...
If you find yourself doing these things over and over again in each test, you may find it useful to bunch these asserts together into a helper method in your test class, which I suspect might be the intended purpose of verifyOrderSummary()
I wrote a selenium code to read values from an excel sheet which contains 2 columns.I need to input these to 2 text boxes in a webpage .I do not want to use TestNG at this point .My issue is every time the browser opens with the webpage for each entry ie each row . Say I have 10 rows in the excel sheet 10 web pages are opened and each would input to the text boxes .How can I rewrite my code to open a single browser and input values one by one .
public class Insert {
public static void main(String[] args)
{
try {
FileInputStream fis = new FileInputStream("F:\\Book4.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("testdata");
for(int count = 1;count<=sheet.getLastRowNum();count++)
{
XSSFRow row = sheet.getRow(count);
System.out.println("Running test case " + row.getCell(0).toString());
runTest(row.getCell(1).toString(),row.getCell(2).toString());
}
fis.close();
} catch (IOException e) {
System.out.println("Test data file not found");
}
}
public static void runTest(String name,String mailid)
{
WebDriver driver=new FirefoxDriver();
driver.get("http://www.deal4loans.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/a[1]")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/input")).sendKeys(name);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/input")).sendKeys(mailid);
}
}
I am assuming the data is as below ('--' is used as a separator for columns):
NAME -- EMAIL-ID
Name1 -- www.email.com1
Name2 -- www.email.com2
Name3 -- www.email.com3
Name4 -- www.email.com4
Name5 -- www.email.com5
Name6 -- www.email.com6
Below code navigates to the browser once and enters in fields at an interval of 2 seconds.
[Works fine when tried with an xls file with "HSSFWorkbook" class]
public class Insert {
static WebDriver driver;
public static void main(String[] args) throws InterruptedException
{
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.deal4loans.com/");
driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/a[1]")).click();
try {
FileInputStream fis = new FileInputStream("F:\\Book4.xlsx");
XSSFWorkbook wb = new HSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("testdata");
for(int count=1;count<=sheet.getLastRowNum();count++)
{
XSSFRow row = sheet.getRow(count);
System.out.println("\n----------------------------");
System.out.println("Running test case " + count);
runTest(row.getCell(0).toString(),row.getCell(1).toString());
}
fis.close();
driver.close();// Closing the firefox driver instance
} catch (IOException e) {
System.out.println("Test data file not found");
}
}
public static void runTest(String name,String mailid) throws InterruptedException
{
System.out.println("Inputing name: "+name+" and mailid: "+mailid);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/input")).clear();
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/input")).clear();
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/input")).sendKeys(name);
driver.findElement(By.xpath("html/body/div[6]/div[1]/div/div[4]/form/table/tbody/tr[3]/td/table/tbody/tr[2]/td[2]/input")).sendKeys(mailid);
System.out.println("Inputted name: "+name+" and mailid: "+mailid);
Thread.sleep(2000); // Sleeping 2 seconds so that each entry is detected.
}
}