Retrieve data from a field using selenium - java

I am a begineer in Automation Testing(using Selenium, JavaLang N Eclipse).
I am trying to fetch few values from a webpage and store them in an excel.
The input values are taken from excel and the output will be stored in an excel.
The problem currently i am facing is, let me tell you with an example.
Firstly, it takes account number say 123 from excel and inputs in to search field and then selects the appropriate account and fetches name and email.
Secondly the next account number say 234 is fetched from excel and inputs in to search field and then it gets the appropriate name and email of that account(234).
I am trying with just two accounts as if now.
So when i see the ouput or rather opens the excel file i only get the last account owner name and number in both the columns.
The result i needed is First account name and email in one column and second account name and email in another column.
I request all the folks to help me out with this!!.
Thanks for looking in to this..
int rc= ws.getRows();
Below is the code:
WebElement s1=driver.findElement(By.xpath("//table[#id='kInfo']/tbody/tr[10]/td"));
//WebElement s1=driver.findElement(By.xpath("//td[#class='tRight']/a"));
String s2=s1.getText();
System.out.println("data:"+s2);
String D1= driver.findElement(By.xpath("//div[#class='vcard clearfix']")).getText();
System.out.println(D1);
Thread.sleep(1000);
/*driver.findElement(By.xpath("//*[#id='homePage']")).click();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Thread.sleep(1000);*/
WritableWorkbook wb1 = Workbook.createWorkbook( new File("C:\\Bhasker-DNT\\Excel\\ouput.xls"));
WritableSheet ws1 = wb1.createSheet("customsheet", 1);
{
for(int count=0;count<4;count++)
{
for(int i=0;i<rc-1;i++)
{
Label label = new Label(i, 0, s2);
ws1.addCell(label);
Label label1 = new Label(i, 1, D1);
ws1.addCell(label1);
}
}
//Label label = new Label(0, 0, s2);
//ws1.addCell(label);
}
wb1.write();
wb1.close();

To fetch element for a div or a selection or a p you need the xpath i suppose you have it.
Than
String name = ""
List<WebElement> your_list= driver.findElements(By.xpath("xpath_stuff or workbook.get(I)"));
for (int i=0; i<your_list.size(); i++) {
// System.out.println(i+ ". " + your_list.get(i).getText());
// here you can write the elements to excel.
//if you need first name you need to just
if(i==(you know which is the first row that conatins the name)
{
name = your_list.get(i).getText();
}
... the same way the email and the other
ws1.addCell(your_list.get(i).getText());
}
wb1.close();
I hope it helps, if not please provide us some example from the html and the from excel.

Related

Trying to get the text out of a List of webelements with Selenium WebDriver

In my code, I try to find all elements with a specific name, then try taking each elements' descendant and get its title, link and price. The price I'm having issues with because it sticks to the price tag of the first element from the WebElements list.
List<WebElement> autos = driver.findElements(By.xpath("//section[contains(#class ,'ui-search-results')]/ol/li//a[#class = 'ui-search-result__content ui-search-link']"));
for(WebElement auto : autos) {
String model = auto.getAttribute("title");
String page = auto.getAttribute("href");
String price = auto.findElement(By.xpath("//span[#class = 'price-tag-fraction']")).getText();
System.out.println(model + page + price);
}
Console is printing model and page just fine but the price is always the same one. I already tested the site and there is a price-tag-fraction per element.
When you use XPath and want to start searching from a specific element, you need to add a . to the start of the XPath. In your case
"//span[#class = 'price-tag-fraction']"
becomes
".//span[#class = 'price-tag-fraction']"
Your updated code
List<WebElement> autos = driver.findElements(By.xpath("//section[contains(#class ,'ui-search-results')]/ol/li//a[#class = 'ui-search-result__content ui-search-link']"));
for(WebElement auto : autos) {
String model = auto.getAttribute("title");
String page = auto.getAttribute("href");
String price = auto.findElement(By.xpath(".//span[#class = 'price-tag-fraction']")).getText();
System.out.println("Model: %s, Page: %s, Price: %s".formatted(model, page, price));
}
NOTE: I changed your print statement to make it easier to read. You could also write these to a CSV file and then open them later in Excel, etc. as a table.

Inserting values into a text fields using automation - Selenium

I have logged into a website page using automation code (Selenium) but now there are fields in which data needs to be entered
But how to do this using Selenium?
How to write the code for it?
Use sendKeys method.
driver.findElement(By.id("InputBox_ID")).sendKeys("Test data");
Use following lines of code to insert value into text.
WebElement Element1 = driver.findElementByName("abc");
Element1.sendKeys("value that you want to enter.");
When searching for a field to fill in, right click on its element in the web page and click "Inspect Element". The ID should be highlighted in the popup menu, and that is going to be the ID You specify into the "By.xpath()" Method from seleniums API.
Here is an example on how to fill in fields for Gmail.
System.setProperty("webdriver.gecko.driver", "/path/to/geckodriver");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver();
driver.get(Links.Register_Gmail);
driver.findElement(By.xpath("//*[#id='FirstName']")).sendKeys(firstname);
driver.findElement(By.xpath("//*[#id='LastName']")).sendKeys(lastname);
driver.findElement(By.xpath("//*[#id='GmailAddress']")).sendKeys(username);
driver.findElement(By.xpath("//*[#id='Passwd']")).sendKeys(password);
driver.findElement(By.xpath("//*[#id='PasswdAgain']")).sendKeys(password);
driver.findElement(By.xpath("//*[#id='BirthMonth']")).click();
driver.findElement(By.xpath("//*[#id=':" + random(1, 9) + "']")).click();
driver.findElement(By.xpath("//*[#id='BirthDay']")).sendKeys("" + random(1, 27));
driver.findElement(By.xpath("//*[#id='BirthYear']")).sendKeys("" + random(1950, 1990));
driver.findElement(By.xpath("//*[#id='Gender']")).click();
driver.findElement(By.xpath("//*[#id=':f']")).click();
driver.findElement(By.xpath("//*[#id='submitbutton']")).click();
driver.findElement(By.xpath("//*[#id='tos-scroll-button']")).click();
driver.findElement(By.xpath("//*[#id='tos-scroll-button']")).click();
driver.findElement(By.xpath("//*[#id='tos-scroll-button']")).click();
driver.findElement(By.xpath("//*[#id='iagreebutton']")).click();
you can do it simply by just right click on the field that you want to fill and click inspect, if you are using firefox then it is quiet simple by using firepath but if you are using chrome then simply right click on the field, click on inspect element and find a unique id of that field and put it inside these below lines
driver.findelement(By.id("")).sendelement(""),
you can use different field than id if you find something else unique.
You can use the below method and call it wherever you want to enter text
public static void enterTextInput(WebElement element, String value) throws InterruptedException{
String val = value;
element.clear();
Thread.sleep(1000);
for (int i = 0; i < val.length(); i++){
char c = val.charAt(i);
String str = new StringBuilder().append(c).toString();
element.sendKeys(str);
}
Thread.sleep(1500);
}

Apache POI : Update cells in a named range

I am using Apache POI library to read/write to xlsx. In my original xlsx, I have a namedrange "XYZ".
I want to update the values of cells within this name range. How can I do that?
I did this:
XSSFName name = workbook.getName("XYZ");
String formula = name.getRefersToFormula();
System.out.println("Formula = " + formula);
Now, I dont know how to get a handle to individual cell in this named range.
Can anyone please point me to the correct API that I can use?
Rgds
Sapan
There is an example from the Busy Developers' Guide for retrieving the cells in the range. Then you can use Cell.setCellValue() to update.
// setup code
String cname = "TestName";
Workbook wb = getMyWorkbook(); // retrieve workbook
// retrieve the named range
int namedCellIdx = wb.getNameIndex(cname);
Name aNamedCell = wb.getNameAt(namedCellIdx);
// retrieve the cell at the named range and test its contents
AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula());
CellReference[] crefs = aref.getAllReferencedCells();
for (int i=0; i<crefs.length; i++) {
Sheet s = wb.getSheet(crefs[i].getSheetName());
Row r = s.getRow(crefs[i].getRow());
Cell c = r.getCell(crefs[i].getCol());
// extract the cell contents based on cell type etc.
}

How to read a csv and create a list of maps out of each line?

I have a Java class to automate some behaviour on the web, my only problem is that now instead of the static data that I have I need to use the data from the csv.
for example:
this is one of the actions in my automation class:
WebElement supplierAddressField = driver.findElement(By.id("FieldaddressOfSupplierLine"));
supplierAddressField.sendKeys("hollywood blvd 34");
So now, instead of the static "supplier address" value I want to iterate on each line of the .sendKeys(csvLineMap.get("supplier address"));
Because in each line I dont need all the headers info, this is why I think it will be the best to just create a list of maps, that each map key will be the header of the csv and the value will be the value for this header in a specific line.
this is the structure of the csv:
Please help me to figure this out...thanksss!!
Apache Commons CSV
For what you are asking for I would recommend you look at Apache Commons CSV. One of the examples from their User Guide matches very closely with with the examples you are trying
Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
String lastName = record.get("Last Name");
String firstName = record.get("First Name");
}
ok, this might be overly complex for what you want, but I always open csv's as excel files because then you can run down the columns. The code for picking up any column would look like this:
Workbook w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet(0);
nom = sheet.getRows();
String[][] SheetArray = new String [2][nom];
// change the first number to the number of columns you want,
// or pick up the number same as you did with rows
Cell cell;
// GETS DATA FROM SHEET AND RUNS THROUGH WHOLE LOOP BELOW FOR EACH REFERENCE
for(int j =0;j<sheet.getRows();j++) // cycles through rows and loads into 2d array
{ // start 6
cell = sheet.getCell(0, j); <- your column number here
cellcont = cell.getContents();
SheetArray[0][j] = cellcont;
// repeat the above block for each column you want
} // end 6
you now have a 2d array with all the info in it which you can handle however you want.
wrap the entire thing in a try .. catch.
With uniVocity-parsers you can parse only the fields you are interested, in any order:
CsvParserSettings parserSettings = new CsvParserSettings();
// Let's extract headers
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.selectFields("Field 5", "Field 1");
//Rows will come organized according to your field selection
List<String[]> allRows = parser.parseAll("path/to/file.csv");
If you prefer, you can easily get a map with the values of all columns:
CsvParserSettings parserSettings = new CsvParserSettings();
// Let's extract headers
parserSettings.setHeaderExtractionEnabled(true);
// To get the values of all columns, use a column processor
ColumnProcessor rowProcessor = new ColumnProcessor();
parserSettings.setRowProcessor(rowProcessor);
CsvParser parser = new CsvParser(parserSettings);
//This will kick in our column processor
parser.parse(new FileReader("path/to/file.csv"));
//Finally, we can get the column values:
Map<String, List<String>> columnValues = rowProcessor.getColumnValuesAsMapOfNames();
Have a look. It is faster than any other parser and you can do much more, such as converting the values and generating java beans.
Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

Fixing some content at the end of first page aspose words java

I am working with apose words java recently.
In my first page I have a table need to merge, which can grow any size, no fixed number of rows and at the end of my first page, I want to keep some content (for example contact details) to be fixed. (Note: I can't keep contact details in Footer or in foot note section because of some formatting I need to ensure which can't maintain in footer or foot note section)
On growing of table as many rows, My content is going down, But I want to fix it at the end of my first page. if table grows bigger in size, wanted to skip the content and render table in next page.
is there any solution/work around for this?
My expected results are like below....
Page 1 Start
dynamic Table row1
dynamic Table row2
dynamic Table row3
Contact Details ,wanted to fix at the end of my first page
Page 1 end
Page 2 Start
dynamic table row 4
dynamic table row 5
........
For your scenario, ideally the contact details should be set in a footer. It is possible, but very risky.
First create a new document, either in Aspose.Words or MS Word, it will be used as a template.
Add a blank table on top
Add contact details, after the blank table
Add a bookmark, after the contact details
Now, using Aspose.Words, you can check the location of the bookmark, every time you are adding a new row in the table. If bookmark is at page 1, add new row to the first table. If bookmark is at page 2, add new row to the second table. Below is the sample code that adds rows to the table, keeping the contact details fixed on page 1.
Template document: Google drive link
Java source code is given below.
public static void main(String[] args)
{
try
{
String template = Common.DATA_DIR + "Contact Template.docx";
String saveDocument = Common.DATA_DIR + "Contact with tables.docx";
String bookmarkNameContact = "ContactEnd";
// Load the template
com.aspose.words.Document wordDoc = new com.aspose.words.Document(template);
DocumentBuilder builder = new DocumentBuilder(wordDoc);
// Find the contacts bookmark
com.aspose.words.Bookmark bookmarkContact = wordDoc.getRange().getBookmarks().get(bookmarkNameContact);
// Set the table with null
com.aspose.words.Table table = null;
// Add some rows
for (int i = 0; i < 50; i++)
{
// If contacts bookmark is on 1st page, add new rows to first table
if (getBookmarkPage(wordDoc, bookmarkContact) == 1)
{
table = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 0, true);
} else
{
// If the contacts bookmark is on second page, add rows to second table
table = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 1, true);
// If there is no second table, create it
if (table == null)
{
table = createNewTable(wordDoc, bookmarkContact);
}
}
// Add rows dynamically to either first or second table
addRow(wordDoc, table, "some text " + i);
}
// Save the document
wordDoc.save(saveDocument);
} catch (Exception ex)
{
System.err.println(ex.getMessage());
}
}
private static com.aspose.words.Table createNewTable(com.aspose.words.Document wordDoc, com.aspose.words.Bookmark bookmarkContact) throws Exception
{
// Get the first table and clone it to create the second one
com.aspose.words.Table firstTable = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 0, true);
com.aspose.words.Table table = (com.aspose.words.Table) firstTable.deepClone(true);
// Add the second table after the bookmark
bookmarkContact.getBookmarkEnd().getParentNode().getParentNode().appendChild(table);
// Delete all its rows
table.getRows().clear();
return table;
}
// Add a new row to the table
private static void addRow(com.aspose.words.Document wordDoc, com.aspose.words.Table table, String text)
{
// Create a new row
com.aspose.words.Row row = new com.aspose.words.Row(wordDoc);
row.getRowFormat().setAllowBreakAcrossPages(true);
// Add it to the table
table.appendChild(row);
// Add cells to the row
for (int iCell = 0; iCell < 4; iCell++)
{
// Create a new cell and set text inside it
com.aspose.words.Cell cell = new com.aspose.words.Cell(wordDoc);
cell.appendChild(new com.aspose.words.Paragraph(wordDoc));
cell.getFirstParagraph().appendChild(new Run(wordDoc, text));
cell.getFirstParagraph().getParagraphFormat().setSpaceAfter(0);
row.appendChild(cell);
}
}
private static int getBookmarkPage(com.aspose.words.Document wordDoc, com.aspose.words.Bookmark bookmarkContact) throws Exception
{
// Find the page number, where our contacts bookmark is
LayoutCollector collector = new LayoutCollector(wordDoc);
return collector.getStartPageIndex(bookmarkContact.getBookmarkEnd());
}
I work with Aspose as Developer Evangelist.

Categories