My first question here! Pardon if i am missing out anything!
I have written code to pick URL from excel and then click on elements in url by fetching corresponding data from the excel sheet. The script runs fine as expected. But it is still throwing Invalid Argument exception after the final run of loop. There are no errors (atleast to my eyes) and i have verified the url links in excel. They are fine. Script currently behaves the way i want. But still i am getting the exception. The final step of driver.close is not performed. Please check the code and let me know where i went wrong.
First column in excel is url. Following columns has text which is picked up by script and used for linktext command to click on the elements in url.
package newpackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidObjectException;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelRead {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","C:\\driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebDriverWait wait=new WebDriverWait(driver, 20);
String baseUrl = "https://google.com/";
driver.get(baseUrl);
FileInputStream fis = new FileInputStream("D:\\test_data.xlsx");
#SuppressWarnings("resource")
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
int s=sheet.getLastRowNum()+1;
for(int i=0; i<s; i++)
{
int k = sheet.getRow(i).getLastCellNum();
XSSFCell cell=sheet.getRow(i).getCell(0);
String url=cell.toString();
driver.get(url);
Thread.sleep(3000);
System.out.println("Launched "+url);
Thread.sleep(5000);
for(int j=1;j<k;j++)
{
String data0=sheet.getRow(i).getCell(j).getStringCellValue();
driver.findElement(By.linkText(data0)).click();
System.out.println(data0+" Saved");
}
}
driver.close();
}
}
Currently getting this after script runs execution:
Exception in thread "main" org.openqa.selenium.InvalidArgumentException: invalid argument
You can check for null as given below. so that, even though you have empty data in excel, it will work.
for(int i=0; i<s; i++)
{
int k = sheet.getRow(i).getLastCellNum();
XSSFCell cell=sheet.getRow(i).getCell(0);
String url=cell.toString();
if(url!=null && !url.isEmpty())
{
driver.get(url);
Thread.sleep(3000);
System.out.println("Launched "+url);
Thread.sleep(5000);
for(int j=1;j<k;j++)
{
String data0=sheet.getRow(i).getCell(j).getStringCellValue();
if(data0!=null && !data0.isEmpty())
driver.findElement(By.linkText(data0)).click();
System.out.println(data0+" Saved");
}
}
}
Related
// this is the exception I am getting
Exception in thread "main" java.lang.ClassCastException: class sun.net.www.protocol.mailto.MailToURLConnection cannot be cast to class java.net.HttpURLConnection (sun.net.www.protocol.mailto.MailToURLConnection and java.net.HttpURLConnection are in module java.base of loader 'bootstrap')
// this is what I tried
package brokenLinks;
import java.io.IOException;
import java.net.HttpURLConnection;
//import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
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 io.github.bonigarcia.wdm.WebDriverManager;
public class ValidateBrokenLinksTest {
public static void main(String[] args) throws IOException {
//set up the webdriver driver
WebDriverManager.chromedriver().setup();
//launch chrome driver
WebDriver driver = new ChromeDriver();
//maximize the window
driver.manage().window().maximize();
//load the url
driver.get("https://testerscafe.in/");
//implicit wait for page to load
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
//get all the links in the webpage using tagName called "a" and store them inside list collection
List<WebElement> elements = driver.findElements(By.tagName("a"));
//get the total number of links available
int size = elements.size();
System.out.println("Number of links available in the webpage :"+size);
//iterate from each link and get the attribute value of each link
for(WebElement links : elements) {
String link = links.getAttribute("href");
//load all the links to URL class
URL url = new URL(link);
//set up the connection
HttpURLConnection connection = (HttpURLConnection)(url.openConnection());
connection.connect();
//validatation
if(connection.getResponseCode()>=400) {
System.out.println(link+" ==> is a broken link");
}
else {
System.out.println(link+" ==> is a valid link");
}
}
//close the webdriver
driver.quit();
}
}
Some of the links on that page are email addresses (info#testerscafe.in). For email links url.openConnection() helpfully returns a MailToURLConnection instead of an HttpURLConnection.
You can exclude the email links and get just the http links with xpath.
Instead of
List<WebElement> elements = driver.findElements(By.tagName("a"));
use
List<WebElement> elements = driver.findElements(By.xpath("//a[starts-with(#href,'http')]"));
See this post regarding how the starts-with xpath works.
In this program I need to write a script to automate the Ecommerce site.
Main activity which is need to automate is like...
1 get URL "this is successfully executed"
2 add item to cart "this is successfully executed"
3 click on cart icon and proceed to checkout. "this is unsuccessfully executed"
for 3 point, my code is not performed. I don't know why?. I think my script is write but placement is wrong. Pls help me to find it. Thanks
package siteTesting;
import java.util.Arrays;
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.firefox.FirefoxDriver;
public class ItemsAddtoCart {
public static void main(String[] args) {
String[] itemNeeded = {"Brocolli","Cauliflower","Cucumber"};
System.setProperty("webdriver.gecko.driver", "D:\\Software\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> products = driver.findElements(By.className("product-name"));
int noOfProduct = products.size();
System.out.println(noOfProduct);
int i;
for(i=0; i<=noOfProduct; i++)
{
String[] NameofProduct = products.get(i).getText().split("-");
String uNameofProduct = NameofProduct[0].trim();
List itemNeededList = Arrays.asList(itemNeeded);
if(itemNeededList .contains(uNameofProduct))
{
System.out.println(uNameofProduct);
driver.findElements(By.xpath("//div[#class='product-action']")).get(i).click();
}
}
'these following lines are not executing, can you tell me why?'
driver.findElement(By.xpath("//a[#class='cart-icon']/img")).click();
driver.findElement(By.xpath("//button[contains(text(),'PROCEED TO CHECKOUT']")).click();
driver.findElement(By.className("promoCode")).sendKeys("rahulshettyacademy");
}
}
Please check below solution with WebDriverWait :
WebDriverWait wait = new WebDriverWait (driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#class='cart-icon']//img[contains(#class,'')]"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'PROCEED TO CHECKOUT')]"))).click();
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#placeholder='Enter promo code']"))).sendKeys("PramoCode");
Note: please add below imports:
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
Working solution
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> products = driver.findElements(By.className("product-name"));
int noOfProduct = products.size();
System.out.println(noOfProduct);
int i;
for(i=0; i<=itemNeeded.length; i++)
{
String[] NameofProduct = products.get(i).getText().split("-");
String uNameofProduct = NameofProduct[0].trim();
List itemNeededList = Arrays.asList(itemNeeded);
if(itemNeededList .contains(uNameofProduct))
{
System.out.println(uNameofProduct);
driver.findElements(By.xpath("//div[#class='product-action']")).get(i).click();
}
}
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#class='cart-icon']//img[contains(#class,'')]"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'PROCEED TO CHECKOUT')]"))).click();
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#placeholder='Enter promo code']"))).sendKeys("PramoCode");
Output:
i am trying to write selenium script which writes pass/fail based on assert.
the problem i am facing here is the assert results are not getting inserted into excel properly. There is some issue with the for loop which i have written. please help me in fixing it.
thanks in advance.
This is the code which i have written
package DDT;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class TestPass extends ExeclUtility
{
WebDriver driver;
Map<String,Object[]> Exp;
#BeforeClass
public void openBrowser()//opening of the browser is done only 1s before executing the test data
{
System.setProperty("webdriver.chrome.driver","C:\\Users\\DELL\\Desktop\\shree\\qsp_java_selenium\\selenium\\selenium_web_driver\\chrome_driver\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("file:///C:/Users/DELL/Desktop/USN%20and%20Sem.html");
}
#Test(dataProvider="TestData")
public void datasend(String username,String phnum,String Exp) throws InterruptedException, RowsExceededException, WriteException
{
WebElement name=driver.findElement(By.id("field1"));
name.clear();
name.sendKeys(username);
WebElement pwd=driver.findElement(By.id("field2"));
pwd.clear();
pwd.sendKeys(phnum);
WebElement but=driver.findElement(By.id("field4"));
but.click();
Alert alert=driver.switchTo().alert();
SoftAssert assertion=new SoftAssert();
for(int i=0;i<6;i++){
try
{
assertion.assertEquals(Exp, alert.getText());// compares the expected result in excel v/s the actual o/p
Testcase="pass";
Label l3=new Label(3,i,Testcase);
writablesh.addCell(l3);
}
catch(Exception e)
{
Testcase="fail";
Label l3=new Label(3,i,Testcase);
writablesh.addCell(l3);
}}
assertion.assertEquals(Exp, alert.getText());
alert.accept();
assertion.assertAll();
Thread.sleep(3000);
}
#AfterClass
public void closeBrowser()//browser is closed 1s after all the test data are executed
{
driver.quit();
}
#DataProvider(name = "TestData")
public Object[][] ExcelData() throws BiffException, IOException
{
String Filepath="D:\\selenium_pgms\\intern_practice\\Book1.xls";
FileInputStream Excelfile=new FileInputStream(Filepath);
Workbook Exbook=Workbook.getWorkbook(Excelfile);
Sheet Exsheet=Exbook.getSheet("Sheet1");
int Rows=Exsheet.getRows();
int Columns=Exsheet.getColumns();
String Testdata[][]= new String[Rows-1][Columns];
int count=0;
for(int i=1;i<Rows;i++)
{
for(int j=0;j<Columns;j++)
{
Cell Excell = Exsheet.getCell(j,i);
Testdata[count][j]=Excell.getContents();
}
count++;
}
Excelfile.close();
return Testdata;
}
}
I tried below two codes. Both didn't select the "Male" option. Could anyone please let me know where I'm doing a mistake.
It's very difficult to post the code in this site. So many conditions
My code:
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class webelements2 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\rpremala003\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.click();
Select dropdown = new Select (driver.findElement(By.xpath(".//*[#id='Gender']/div")));
dropdown.selectByIndex(1);
}
}
Even I used sendkeys method. But it didn't work for me
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class webelements2 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\rpremala003\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.sendKeys("Male");
google.click();
}
Please suggest me how to overcome this problem
You can use Select() with <select>, <option> elements only. In this current case you can simply click() on drop-down and then click() to choose required option:
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.click();
WebElement option = (driver.findElement(By.xpath("//div[text()='Male']"));
option.click();
You might also need to wait until option to be clickable:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement option = wait.until(elementToBeClickable(By.xpath("//div[text()='Male']")));
option.click();
Simply use this and let me know if it works for you:
For Female
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":e")).click();
For Male
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":f")).click();
For Other
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":g")).click();
For Rather not say
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":h")).click();
And if you need for sign-up gmail, I tried Once:
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
driver.findElement(By.xpath(".//*[#id='FirstName']")).sendKeys("Name");
driver.findElement(By.xpath(".//*[#id='LastName']")).sendKeys("Last name");
driver.findElement(By.xpath(".//*[#id='GmailAddress']")).sendKeys("Email id");
driver.findElement(By.xpath(".//*[#id='Passwd']")).sendKeys("Password");
driver.findElement(By.xpath(".//*[#id='PasswdAgain']")).sendKeys("Password Again");
//Input the month
List<WebElement> month_dropdown = driver.findElements(By.xpath(".//*[#id='BirthMonth']/div"));
//iterate the list and get the expected month
Thread.sleep(3000);
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
Thread.sleep(3000);
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
driver.findElement(By.id("BirthMonth")).click();
driver.findElement(By.id(":3")).click();
driver.findElement(By.xpath(".//*[#id='BirthDay']")).sendKeys("14");
driver.findElement(By.xpath(".//*[#id='BirthYear']")).sendKeys("1988");
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":e")).click();
driver.findElement(By.xpath(".//*[#id='RecoveryPhoneNumber']")).sendKeys("4694222863");
driver.findElement(By.xpath(".//*[#id='RecoveryEmailAddress']")).sendKeys("recovery email id");
driver.findElement(By.id("submitbutton")).click();
Thread.sleep(3000L);
Below is the code to create a FB account. I have excel sheet with Test data to create them. How to import that data into the below code???
Code:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
public class Facebookup {
public static void main (String args[]) throws InterruptedException
{
WebDriver gm = new FirefoxDriver();
gm.manage().window().maximize();
gm.get("https://www.facebook.com/");
gm.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
gm.findElement(By.xpath(".//*[#id='u_0_1']")).sendKeys("Tester");
gm.findElement(By.xpath(".//*[#id='u_0_3']")).sendKeys("Dravid");
gm.findElement(By.xpath(".//*[#id='u_0_5']")).sendKeys("testprod2000#gmail.com");
gm.findElement(By.xpath(".//*[#id='u_0_8']")).sendKeys("testprod2000#gmail.com");
gm.findElement(By.xpath(".//*[#id='u_0_a']")).sendKeys("Naren1234");
gm.findElement(By.xpath(".//*[#id='month']")).click();
Thread.sleep(2000);
gm.findElement(By.xpath(".//option[#value = '1']")).click();
gm.findElement(By.xpath(".//*[#id='day']")).click();
Thread.sleep(2000);
gm.findElement(By.xpath(".//option[#value = '8']")).click();
gm.findElement(By.xpath(".//*[#id='year']")).click();
Thread.sleep(2000);
gm.findElement(By.xpath(".//option[#value = '1991']")).click();
Thread.sleep(2000);
gm.findElement(By.xpath(".//*[#id='u_0_e']")).click();
gm.findElement(By.xpath(".//*[#id='u_0_i']")).click();
}
}
You can use JXL Java library which has a method to read data from excel sheets.
The jar can be downloaded from http://www.java2s.com/Code/Jar/j/Downloadjxljar.htm