Use Excel to automate Selenium test in Apache POI - selenium

I am a complete beginner in Selenium and I am not able to automate the Selenium code below. I have tried numerous methods but I am still getting issues with automating the run from getting the data from excel. I have even tried using the TestNG method as well but no luck I am stuck on this part not. Can someone help on how to automate this code without changing the row numbers in this step for (int i= 1; i<=noOfRows ; i++).
The code used:
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("driver location");
WebDriver driver = new FirefoxDriver();
driver.get("link");
FileInputStream file = new FileInputStream("xcel file location");
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet= workbook.getSheet("SO Reg");
int noOfRows = sheet.getLastRowNum(); // returns the row count
System.out.println("No. of Records in the Excel Sheet:" + noOfRows);
int cols=sheet.getRow(1).getLastCellNum();
System.out.println("No. of Records in the Excel Sheet:" + cols);
for (int i= 1; i<=6; i++)
{
String SO_Name = row.getCell(0).getStringCellValue();
String Contact_Person = row.getCell(1).getStringCellValue();
String Address_1 = row.getCell(2).getStringCellValue();
String Address_2 = row.getCell(3).getStringCellValue();
String City = row.getCell(4).getStringCellValue();
String State = row.getCell(5).getStringCellValue();
String ZipCode = row.getCell(6).getStringCellValue();
String Phone_Number = row.getCell(8).getStringCellValue();
String Username = row.getCell(9).getStringCellValue();
String Email = row.getCell(10).getStringCellValue();
String Re_Type_Email = row.getCell(11).getStringCellValue();
//Registration Process
driver.findElement(By.cssSelector("p.text-white:nth-child(4) > a:nth-child(1)")).click(); //create an account
Thread.sleep(5000);
//Enter Data information
driver.findElement(By.id("SOName")).sendKeys(SO_Name);
driver.findElement(By.xpath("//*[#id=\"ContactPerson\"]")).sendKeys(Contact_Person);
driver.findElement(By.xpath("//*[#id=\"AddressLine1\"]")).sendKeys(Address_1);
driver.findElement(By.xpath("//*[#id=\"AddressLine2\"]")).sendKeys(Address_2);
driver.findElement(By.id("City")).sendKeys(City);
driver.findElement(By.id("State")).sendKeys(State);
driver.findElement(By.id("ZipCode")).sendKeys(ZipCode);
driver.findElement(By.id("Phone")).sendKeys(Phone_Number);
driver.findElement(By.xpath("//*[#id=\"UserName\"]")).sendKeys(Username);
driver.findElement(By.xpath("//*[#id=\"Email\"]")).sendKeys(Email);
driver.findElement(By.xpath("//*[#id=\"RandText\"]")).sendKeys(Re_Type_Email);
driver.findElement(By.id("ConfirmBox")).click();
driver.findElement(By.xpath("/html/body/app-root/app-soregistration/div[2]/div/div/div/div/form[2]/div/div[12]/div/button[1]")).click();
driver.findElement(By.cssSelector(".btn-green-text-black")).click(); //finish button
driver.findElement(By.cssSelector("p.text-white:nth-child(4) > a:nth-child(1)")).click(); //create an account
Thread.sleep(5000);
}
}
}
}
java
selenium
automation
katalon-studio

Related

can we use common data provider method for various test cases in selenium? Can i pass the excel path and sheet name to common data provider?

I have more than one test case naming as classAtest1, classAtest2,classAtest1 etc
Now i am doing each and every class i have to write data provider method seprately
but i want to write only one data provider method and i can able to use it with all the classes by passing excel, path and sheet name
**#DataProvider(name="getData")** // supplying data for a test method.
public Object[][] getData() throws IOException
{
FileInputStream fis = new FileInputStream("**Z:\\MAANTTIANS\\folder\\Excel Sheets\\QestionBank.xlsx**"); // Your .xlsx file name along with path
excelWorkbook = new XSSFWorkbook(fis);
// Read sheet inside the workbook by its name
excelSheet = excelWorkbook.getSheet("**MTFQuestion**"); //Your sheet name
// Find number of rows in excel file
System.out.println("First Row Number/index:"+ excelSheet.getFirstRowNum() + " *** Last Row Number/index:"+ excelSheet.getLastRowNum());
int rowCount = excelSheet.getLastRowNum() - excelSheet.getFirstRowNum()+1;
int colCount = excelSheet.getRow(0).getLastCellNum();
System.out.println("Row Count is: " + rowCount+ " *** Column count is: " + colCount);
Object data[][] = new Object[rowCount-1][colCount];
for (int rNum = 2; rNum <= rowCount; rNum++)
{
for (int cNum = 0; cNum < colCount; cNum++)
{
data[rNum - 2][cNum] = getCellData("MTFQuestion", cNum, rNum); //Your sheet name
}
System.out.println();
}
return data;
}
}
Yes we can use.
You can pass DataProvider name to each #Test method, TestNG will execute each test case with alphabetic order.

Selecting Date on a Page using selenium Webdriver

This is the website I am testing https://www.sydneyairport.com.au/go/car-parking.aspx , I am almost done , but have been stuck in a single issue .
I have selected "date and time" from entry-date section but cannot select "date and time" from exit-date section.
I am clueless why I am not able to it since its the same structure for both and I was able to do it for entry-date ,I don't understand what changes for exit date section . I am new to selenium and will appreciate if anybody helps me out .
This is what I have written to select date and time in entry date section .
public void selectDate(WebDriver driver, String fromDate, String toDate) {
// selects from date
WebElement dateButton = driver.findElement(By.id("period_picker_0"));
dateButton.click();
WebElement datepicker = driver.findElement(By.xpath("//div[#class='period_picker_days']/table/tbody/tr/td[1]"));
selectDate(datepicker, fromDate);
WebElement timeBox = driver.findElement(By.xpath("//div[#class='period_picker_work']/div[2]/input"));
timeBox.sendKeys("");
WebElement time = driver
.findElement(By.xpath(".//*[#id='timepicker_box_start']/div/div[2]/div/div[1]/div[13]"));
time.click();
// Selects to date
WebElement dateButton2 = driver.findElement(By.id("period_picker_1"));
dateButton2.click();
// dateButton.click();
WebElement datepicker2 = driver
.findElement(By.xpath("//div[#class='period_picker_days']/table/tbody/tr/td[2]"));
selectDate(datepicker2, toDate);
WebElement timeBoxEnd = driver.findElement(By.xpath("//div[#class='period_picker_work']/div[2]/input"));
timeBoxEnd.sendKeys("");
WebElement timeEnd = driver
.findElement(By.xpath(".//*[#id='timepicker_box_end']/div/div[2]/div/div[1]/div[13]"));
timeEnd.click();
}
public int selectDate(WebElement datepicker, String date) {
int ele = 0;
List<WebElement> rows_table = datepicker.findElements(By.tagName("tr"));
int rows_count = rows_table.size();
for (int row = 0; row < rows_count; row++) {
// To locate columns(cells) of that specific row.
List<WebElement> Columns_row = rows_table.get(row).findElements(By.tagName("td"));
// To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
// Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
// To retrieve text from that specific cell.
if (Columns_row.get(column).getText().equals(date)) {
ele = column;
Columns_row.get(column).click();
}
}
}
return ele;
}
I did lot of work for this code, You are using tr and td. I would suggest there is no need of it.
See the code I'm using, i am able to select both date easily. Hope this help you..
driver.get("https://www.sydneyairport.com.au/go/car-parking.aspx");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='period_picker_0']")).click();
Actions a = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver,20);
WebElement entrydate= driver.findElement(By.xpath(".//*[#id='body']/div[1]/div[2]/div[1]/table/tbody/tr/td[1]/table/tbody/tr[5]/td[5]"));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='body']/div[1]/div[2]/div[1]/table/tbody/tr/td[1]/table/tbody/tr[5]/td[5]")));
a.moveToElement(entrydate).build().perform();
Thread.sleep(5000L);
entrydate.click();
WebElement entrytime= driver.findElement(By.xpath(".//*[#id='timepicker_box_start']/div/div[2]/div/div[1]/div[15]"));
a.moveToElement(entrytime).build().perform();
Thread.sleep(5000L);
entrytime.click();
WebElement exitdate= driver.findElement(By.xpath(".//*[#id='body']/div[2]/div[2]/div[1]/table/tbody/tr/td[1]/table/tbody/tr[6]/td[5]"));
a.moveToElement(exitdate).build().perform();
Thread.sleep(5000L);
exitdate.click();
WebElement exittime= driver.findElement(By.xpath(".//*[#id='timepicker_box_end']/div/div[2]/div/div[1]/div[15]"));
a.moveToElement(exittime).build().perform();
Thread.sleep(5000L);
exittime.click();
Please do reply, how you find this and reply back to me for further query.
Happy Learning. :-)

How to save Excel Table as a Picture using vb.net?

I'm trying to save tables from excel sheets as pictures. Is there a way to just put that table on the clipboard and save it? This is what I've got so far but the library referenced is not there?
Thank you in advance!
-Rueben Ramirez
Public Sub extract_excelTable(ByRef data_file As String, ByRef app1 As excel.Application, ByRef sheet_name As String)
'defining new app to prevent out of scope open applications
Dim temp_app As excel.Application = app1
Dim workbook As excel.Workbook = temp_app.Workbooks.Open(Path.GetFullPath(data_file))
temp_app.Visible = False
For Each temp_table As excel.DataTable In workbook.Worksheets(sheet_name)
temp_table.Select()
'temp_app.Selection.CopyAsPicture?
Next
End Sub
I'm not going to write any code here, but I will outline a solution for you that will work. Note that this will not reproduce the formatting of the excel document, just simply get the data from it, and put it on an image in the same column/row order as the excel file.
STEP 1:
My solution to this problem would be to read the data from the excel file using an OLEDB connection as outlined in the second example of this post: Reading values from an Excel File
Alternatively, you may need to open the document in excel and re-save it as a CSV if it's too large to fit in your computer's memory. I have some code that reads a CSV into a string list in C# that may help you:
static void Main(string[] args)
{
string Path = "C:/File.csv";
System.IO.StreamReader reader = new System.IO.StreamReader(Path);
//Ignore the header line
reader.ReadLine();
string[] vals;
while (!reader.EndOfStream)
{
ReadText = reader.ReadLine();
vals = SplitLine(ReadText);
//Do some work here
}
}
private static string[] SplitLine(string Line)
{
string[] vals = new string[42];
string Temp = Line;
for (int i = 0; i < 42; i++)
{
if (Temp.Contains(","))
{
if (Temp.Substring(0, Temp.IndexOf(",")).Contains("\""))
{
vals[i] = Temp.Substring(1, Temp.IndexOf("\",", 1) - 1);
Temp = Temp.Substring(Temp.IndexOf("\",", 1) + 2);
}
else {
vals[i] = Temp.Substring(0, Temp.IndexOf(","));
Temp = Temp.Substring(Temp.IndexOf(",") + 1);
}
}
else
{
vals[i] = Temp.Trim();
}
}
return vals;
}
STEP 2:
Create a bitmap object to create an image, then use a for loop to draw all of the data from the excel document onto the image. This post had an example of using the drawstring method to do so: how do i add text to image in c# or vb.net

How to select dropdown value in selenium webdriver using Testng?

How can we select the dropdown value in selenium webdriver using Testng?
Selecting dropdown values in selenium webdriver is not a part of TestNG, it's part of selenium+java code.
Use below code for reference ::
public class temp {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.shoppersstop.com/shoes/kids-shoes/all/brand/kittens.html");
WebElement selectElement = driver.findElement(By
.xpath("//select[#class='subCatThree' and #name='category']"));
Select select = new Select(selectElement);
List<WebElement> options = select.getOptions();
for (WebElement option : options) {
System.out.println(option.getText());
if (option.getText().equals("Girls ( 3 Years & Above)")) {
option.click();
break;
}
}
}
If you want to select by value
Select select = new Select(driver.findelement(By.xpath("write the xpath of dropdown")));
select.selectByValue("write value here");
If you want to select by Text
Select select = new Select(driver.findelement(By.xpath("write the xpath of dropdown")));
select.selectByVisibleText("write text here");
How do we convert this code to use Selenium WebDriver
If Browser("UOB").Page("pgeSetCustomLimits").Exist(intSyncTime*1) Then
Set oDesc=Description.Create
oDesc("micclass").Value = "WebElement"
oDesc("html id").Value = "limitsInput_CI_form_label_div"
Set ObjEle =
Browser("UOB").Page("pgeSetCustomLimits").ChildObjects(oDesc)
For i=0 to ObjEle.count-1
strWebEleText = ObjEle(i).getRoProperty("innertext")
'print strWebEleText
If Instr(strWebEleText,strPaymentType) Then
intRow = i
Exit For
End If
Next
End If

How to use Lucene IndexReader to read index in version 4.4?

For the just the sake of learning I've created an index from 1 file and wanted to search it. I am using Lucene Version 4.4. I know that indexing part is true.
tempFileName is the name of file which contains tokens and this file has the following words :
"odd plus odd is even ## even plus even is even ## odd plus even is odd ##"
However when I provide a query it returns nothing. I can't see what would be the problem. Any help is greatly appreciated.
Indexing part :
public void startIndexingDocument(String indexPath) throws IOException {
Analyzer analyzer = new WhitespaceAnalyzer(Version.LUCENE_44);
SimpleFSDirectory directory = new SimpleFSDirectory(new File(indexPath));
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44,
analyzer);
IndexWriter writer = new IndexWriter(directory, config);
indexDocs(writer);
writer.close();
}
private void indexDocs(IndexWriter w) throws IOException {
Document doc = new Document();
File file = new File(tempFileName);
BufferedReader br = new BufferedReader(new FileReader(tempFileName));
Field field = new StringField(fieldName, br.readLine().toString(),
Field.Store.YES);
doc.add(field);
w.addDocument(doc);
}
Searching part :
public void readFromIndex(String indexPath) throws IOException,
ParseException {
Analyzer anal = new WhitespaceAnalyzer(Version.LUCENE_44);
QueryParser parser = new QueryParser(Version.LUCENE_44, fieldName, anal);
Query query = parser.parse("odd");
IndexReader reader = IndexReader.open(NIOFSDirectory.open(new File(
indexPath)));
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
searcher.search(query, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// display
System.out.println("fieldName =" + fieldName);
System.out.println("Found : " + hits.length + " hits.");
for (int i = 0; i < hits.length; i++) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i + 1) + ". " + d.get(fieldName));
}
reader.close();
}
The problem is that you are using a StringField. StringField indexes the entire input as a single token. Good for atomic strings, like keywords, identifiers, stuff like that. Not good for full text searching.
Use a TextField.
StringField have a single token. So, I try to test with simple code.
for example #yns~ If you have a file that this is cralwer file and this contents hava a single String.
ex) file name : data03.scd , contents : parktaeha
You try to search with "parktaeha" queryString.
You get the search result!
field name : acet, queryString parktaeha
======== start search!! ========== q=acet:parktaeha Found 1 hits. result array length :1 search result=> parktaeha
======== end search!! ==========
Look under the code. This code is test code.
while((target = in.readLine()) != null){
System.out.println("target:"+target);
doc.add(new TextField("acet",target ,Field.Store.YES)); // use TextField
// TEST : doc.add(new StringField("acet", target.toString(),Field.Store.YES));
}
ref url