I am using selenium webdriver to output first three records by using the Advanced Search of Linkedin in an excel sheet however I am not getting all the values of 'name' and 'description' fields except one. Please look into this
public void testExport() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("session_key-login")).clear();
driver.findElement(By.id("session_key-login")).sendKeys("#####");
driver.findElement(By.id("session_password-login")).clear();
driver.findElement(By.id("session_password-login")).sendKeys("#####");
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#value='Sign In']")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("advanced-search")).click();
driver.findElement(By.id("adv-O-N-ffs")).click();
new Select(driver.findElement(By.id("advscountryCode"))).selectByVisibleText("United States");
driver.findElement(By.xpath(".//*[#id='adv-facet-CC']/fieldset/legend")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='adv-facet-CC']/fieldset/div/div/div/button")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='adv-facet-CC']/fieldset/div/div/input")).sendKeys("Leadmd");
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='pagekey-voltron_federated_search_internal_jsp']/div[1]/div/div[2]/ul/li[1]/img")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='adv-facet-CC']/fieldset/div/div/div/button")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='adv-facet-CC']/fieldset/div/div/input")).sendKeys("cloudwords");
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='pagekey-voltron_federated_search_internal_jsp']/div[1]/div/div[2]/ul/li[1]/img")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='adv-facet-CC']/fieldset/div/div/div/button")).click();
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='adv-facet-CC']/fieldset/div/div/input")).sendKeys("Grazitti");
Thread.sleep(1000);
driver.findElement(By.xpath(".//*[#id='pagekey-voltron_federated_search_internal_jsp']/div[1]/div/div[2]/ul/li[1]/img")).click();
Thread.sleep(1000);
driver.findElement(By.id("advs-title")).sendKeys("Marketing");
driver.findElement(By.name("submit")).click();
Thread.sleep(1000);
String name, designation;
for(int i = 0; i < 3; i++) {
int j = i + 1 ;
name = driver.findElement(By.xpath(".//*[#id='results']/li["+j+"]/div/h3/a")).getText();
System.out.println("data1 = " + name);
designation = driver.findElement(By.xpath(".//*[#id='results']/li["+j+"]/div/p")).getText();
System.out.println("data2 = " + designation);
File fExcel = new File("C:\\Users\\Master\\Desktop\\new.xls");
WritableWorkbook writableBook = Workbook.createWorkbook(fExcel);
writableBook.createSheet("Data", 0);
WritableSheet writableSheet = writableBook.getSheet(0);
Label data1 = new Label(j, 1, name);
writableSheet.addCell(data1);
Label data2 = new Label(j, 1, designation);
writableSheet.addCell(data2);
writableBook.write();
writableBook.close();
}
}
You are creating a new Excel file effectively overwriting the previous one by creating the sheet inside the for loop.
Try modifying the for loop part of your code as below
File fExcel = new File("C:\\Users\\Master\\Desktop\\new.xls");
WritableWorkbook writableBook = Workbook.createWorkbook(fExcel);
writableBook.createSheet("Data", 0);
WritableSheet writableSheet = writableBook.getSheet(0);
for(int i = 0; i < 3; i++) {
int j = i + 1 ;
name = driver.findElement(By.xpath(".//*[#id='results']/li["+j+"]/div/h3/a")).getText();
System.out.println("data1 = " + name);
designation = driver.findElement(By.xpath(".//*[#id='results']/li["+j+"]/div/p")).getText();
System.out.println("data2 = " + designation);
Label data1 = new Label(j, i, name);
writableSheet.addCell(data1);
Label data2 = new Label(j, i, designation);
writableSheet.addCell(data2);
}
writableBook.write();
writableBook.close();
Also new Label (j,1,name) means data is getting added to the first row one after other.
You may change it too new Label (j,i,name) so that each name-designation pair will be added to a new row.
Let me know if this helps you
Related
I'm currently new to TestNG using java. I'm trying to read the values from an excel using poi apache 4.0
public static void read2dRowExcelFile2(String filePath) throws IOException {
try {
FileInputStream fis = new FileInputStream(new File(filePath));
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheet("PerLocation");
Object[][] tableArr = new String[sheet.getLastRowNum() + 1][];
int arrNo1 = 0;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
int arrNo2 = 0;
for (int j = 0; j < row.getLastCellNum(); j++) {
String cellValue = row.getCell(j).getStringCellValue();
System.out.println(acellValue);
//tableArr[arrNo1][arrNo2] = cellValue;
System.out.println("test");
arrNo2++;
}
arrNo1++;
}
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Code above displays the values on the console. My goal is to store those values to an Object. Something like [{London, Blue},{Tokyo,Yellow},{Manila,Red}] so I can pass them to a dataProvider
If I run the code above, it displays :
London
BLue
Tokyo
Yellow
Manila
Red
But If i uncomment this line :
//tableArr[arrNo1][arrNo2] = cellValue;
The output is only :
London
03-08-19 : After I enabled stacktrace, it says : java.lang.NullPointerException
which pertains to this code :
tableArr[arrNo1][arrNo2] = cellValue;
From your code,
Object[][] tableArr = new String[sheet.getLastRowNum() + 1][];
At the time of initialization of array, your are setting size of first dimension but not the second . You need to initialize array for second dimension before you access it.
Refer below example:
public static void main(String[] args) {
//read rows size
int numOfRows = 3;
String[][] tableArr = new String[numOfRows][];
for (int row = 0; row <3; row++) {
//read columns size
int numOfColsInRow = 3;
tableArr[row]=new String[numOfColsInRow];
for (int col = 0; col < 3; col++) {
String cellValue = "cell-" + row+""+col;//read cell value
tableArr[row][col] = cellValue;
}
}
for(String[] row: tableArr) {
System.out.println(Arrays.toString(row));
}
}
Running above code with generate expected output:
[cell-00, cell-01, cell-02]
[cell-10, cell-11, cell-12]
[cell-20, cell-21, cell-22]
To reproduce your problem you can try commenting line which initialize array for second dimension in the code and you will see Exception in thread "main" java.lang.NullPointerException
.
//tableArr[row]=new String[numOfColsInRow];
To avoid all such issues you also can check if any exiting TestNG data-provider extension satisfies your need.
I want to store Rows and Column of web table into array list, then will verify the data. I am available to print the rows but how I will store the rows.
public void verifyTable() {
String Test = driver.findElement(loggedinas).getText();
boolean isDue = false;
isDue = UtilClass.isElementPresent(driver, TableContent);
if (isDue) {
if (isDue = driver.findElement(TableContent).getText() != null)
;
System.out.println("Action Required = " + isDue);
WebElement table_element = driver.findElement(Table);
List<WebElement> tr_collection = table_element
.findElements(TableRow);
System.out.println("Number Of Due = " + tr_collection.size());
int row_num, col_num;
row_num = 1;
for (WebElement trElement : tr_collection) {
List<WebElement> td_collection = trElement.findElements(By.xpath("td"));
System.out.println("--NUMBER OF COLUMNS = "
+ td_collection.size() + "--");
col_num = 1;
for (WebElement tdElement : td_collection) {
// System.out.println("Pending # "+row_num+", col # "+col_num+
// "text="+tdElement.getText());
System.out.printf(" # " + tdElement.getText(), " ID "
+ tdElement.getText());
col_num++;
}
row_num++;
}
Thank you!
I had done something similar, please check this function bellow, this will give you an idea
public void manageUserDataGrid(WebDriver driver){
WebElement table = driver.findElement(By.xpath("//*[#id='ReportTable']"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
List<WebElement> column = table.findElements(By.tagName("td"));
List<String> value = new ArrayList<String>();
System.out.println(rows.size());
for (int j=0; j<column.size(); j++){
System.out.println(column.get(j).getText());
value.add(column.get(j).getText());
}
if (value.contains("coadminss")){
System.out.println("Value found");
}
else{
System.out.println("Not Found");
}
}
I want to get text from all the check boxes given in a drop down box in order to compare those values with db. Please help me. I am able to count the size by options.size(), but unable to get the text/strings to compare with each string in db.
//Click on Select Box
Thread.sleep(500);
driver.findElement(By.xpath(".//*[#id='DivZone']/div/button")).click();
Thread.sleep(500);
List<WebElement> options =
driver.findElements(By.xpath("//input[contains(#name,
'multiselect_ddlZone')]"));
//List<WebElement> options = driver.findElements(By.cssSelector(".ui-
corner-all.ui-state-hover>span"));
List<String> all_elements_text=new ArrayList<>();
if(region!=null)
{
for(int i=1; i<options.size(); i++)
{
all_elements_text.add(options.get(i).getText());
System.out.println(options.get(i).getText());
boolean isThere = false;
for (int j = 0; j < region.size(); j++)
{
if
(options.get(i).getText().equalsIgnoreCase(region.get(j))) {
// Code to display warning
isThere = true;
}
}
if(isThere)
System.out.println(options.get(i).getText()+" is matched
with Database data");
else
System.out.println(options.get(i).getText()+" is not matched
with Database data");
}
}
If unfortunately getText() doesn't work, you should try using getAttribute("textContent") as below :-
System.out.println(options.get(i).getAttribute("textContent"));
Or try using getAttribute("innerHTML") as below :-
System.out.println(options.get(i).getAttribute("innerHTML"));
Right now, each "option" is an "input" WebElement, which will not have any text.
You may want to try searching for the list items, then pulling out the span content:
List<WebElement> options = driver.findElements(By.cssSelector("ul.ui-multiselect-checkboxes li label[for*='ddlZone'] span"));
Gave it a try on "www.tripadvisor.in", and able to make it (Used 'break' statement just to limit the loop in the example). Below is the code I tried on
public class SelectList {
WebDriver driver;
By currencyDrop = By.xpath(".//*[#id='CURRENCYPOP']/span");
By currency = By.xpath(".//*[#id='GLOBAL_CURRENCY_PICKER']/ul/li");
#Test
public void f() throws InterruptedException {
driver = new FirefoxDriver();
driver.get("https://www.tripadvisor.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(currencyDrop).click();
//Below is the list of options present in dropdown(per DB)
String[] expList = {"INR ₹ Indian Rupees",
"USD US$ U.S. Dollars",
"EUR € Euros"};
List <WebElement>countryList = driver.findElements(currency);
int i =0;
for(WebElement curr:countryList){
if (i>2){
break;
}
if (curr.getText().equals(expList[i])){
System.out.println("ActCurrency" + curr.getText());
System.out.println("ExpCurrency" + expList[i]);
i++;
}
}
}
}
Test case:
Check box needs to be checked and corresponding drop down value needs to be selected.
Issue:
Cannot click on the element as another element is overlapped on the required element. Error is
Element is not clickable at point (898.9500122070312, 16.5). Other
element would receive the click:
Command duration or timeout: 76 milliseconds
public class ProfileCreation {
public static WebDriver driver ;
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
System.out.println("Profile Name ===>"+ timeStamp );
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://suite.simplify360.com");
driver.findElement(By.cssSelector(".form-login.first-input")).sendKeys("alexxm360#gmail.com");
driver.findElement(By.id("login_password")).sendKeys("Simplify360#");
driver.findElement(By.id("rp")).click();
driver.findElement(By.linkText("Listen")).click();
driver.findElement(By.xpath("//input[contains(#onclick,'createNewProfile();')]")).click();
driver.findElement(By.xpath("//input[#id='dashboardName']")).sendKeys(timeStamp);
System.out.println("Profile Name ===>"+ timeStamp );
WebElement slider = driver.findElement(By.xpath("//*[#id='slider-range-max']/a[2]"));
Actions move = new Actions(driver);
Action action = (Action) move.dragAndDropBy(slider, 30, 0).build();
action.perform();
WebElement permissionDropDown = driver.findElement(By.id("actionPerm"));
Select oselect = new Select(permissionDropDown);
List <WebElement> elementCount = oselect.getOptions();
// System.out.println("Count of Options"+elementCount.size());
int iSize = elementCount.size();
// For priting the values in permission
/*for(int i =0; i<iSize ; i++){
String sValue = elementCount.get(i).getText();
System.out.println("permissoin Values"+sValue);
}*/
oselect.selectByVisibleText("OPEN");
oselect.selectByVisibleText("WARN");
oselect.selectByVisibleText("BLOCK");
if (driver.findElements(By.cssSelector("a.cb-enable.selected")).size() > 0 ) {
driver.findElement(By.xpath("//span[contains(.,'Off')]")).click();
} else {
driver.findElement(By.xpath("//span[contains(.,'On')]")).click();
}
if(driver.findElements(By.id("reassignPeriodMins")).size() > 0){
WebElement caseAssociateMin = driver.findElement(By.id("reassignPeriodMins"));
Select timeSelect = new Select(caseAssociateMin);
WebElement firstSelectedOption = timeSelect.getFirstSelectedOption();
System.out.println("Default Selected Time"+firstSelectedOption.getText());
timeSelect.selectByVisibleText("45");
}
if(driver.findElements(By.id("replySetting")).size() > 0){
WebElement replySetting = driver.findElement(By.id("replySetting"));
Select replyType = new Select(replySetting);
WebElement firstSelectedOption = replyType.getFirstSelectedOption();
System.out.println("Default Selected Time"+firstSelectedOption.getText());
replyType.selectByVisibleText("REPLY");
replyType.selectByVisibleText("REPLYALL");
}
System.out.println( "checkboxes" + driver.findElements(By.className("shareCheck")).size());
int sizeOfUsers = driver.findElements(By.className("shareCheck")).size();
for (int i = 1; i <= sizeOfUsers; i++) {
boolean fname = driver.findElement(By.xpath("//*[#id='basketusers']/tbody/tr["+ i +"]/td[3]/input")).isEnabled();
if (fname == false){
String disblaedEmailID = driver.findElement(By.xpath("//*[#id='basketusers']/tbody/tr["+ i +"]/td[2]/div")).getText();
String loginEmailId = "nagarjun.reddy#in-rev.com";
if( disblaedEmailID == loginEmailId){
System.err.println("Check Box is disabled ====>"+disblaedEmailID);
}
System.err.println("i value==>"+ i);
i++;
System.err.println("selected email id will be =="+ driver.findElement(By.xpath(".//*[#id='basketusers']/tbody/tr["+i+"]/td[2]/div")).getText() );
//ISSUE IS HERE. CANNOT MOVE TO THE REQUIRED ELEMENT
jse.executeScript("arguments[0].scrollIntoView(true);",driver.findElement(By.xpath(".//*[#id='basketusers']/tbody/tr["+i+"]/td[2]/div")));
driver.findElement(By.xpath("//*[#id='basketusers']/tbody/tr["+ i +"]/td[3]/input")).click();
Select roleSelect = new Select(driver.findElement(By.xpath(".//*[#id='basketusers']/tbody/tr["+i+"]/td[4]/select")));
System.err.println("First selected role ====>"+ roleSelect.getFirstSelectedOption().getText());
roleSelect.selectByVisibleText("PROFILE AGENT");
System.err.println("Changed role ====>"+ roleSelect.getFirstSelectedOption().getText());
}
// System.err.println( driver.findElement(By.xpath("//*[#id='basketusers']/tbody/tr["+ i +"]/td[3]/input")));
}
// driver.findElement(By.xpath("//input[#value='Next']")).click();
}
}
Try adding a scroll up like this.
jse.executeScript("window.scrollBy(0,-250)", "");
This will just make the chekbox not to hid eunder navbar.
i tried locally and it worked.
Am New to selenium Webdriver i have one project called Smoke testing .ie testing all the websites links are working fine or not .if any link is broken or not working means that test report sending email to the specified url.Actually i have write some codes for testing all the links and all the websites are getting from excel sheet problem is if the link is not working bt it shows the result as it is working nu so i cannot know the exact solution.here am attaching that codes Especially all the websites are made up of Wordpress.
public class LinktestTest
{
public static WebDriver driver;
#Test
public void findurl() throws Throwable, IOException {
FileInputStream fi = new FileInputStream("D:\\sample.xls");
Workbook wb = Workbook.getWorkbook(fi);
//driver = new FirefoxDriver();
Sheet s = wb.getSheet(0);
System.out.println("Program Started"+s.getName());
System.out.println(s.getRows());
for (int row = 0; row <= s.getRows()-1; row++)
{
driver = new FirefoxDriver();
String Urllist = s.getCell(0, row).getContents().toString();
System.out.println("Urllist" + Urllist);
driver.get(Urllist);
List<WebElement> linkElements = driver.findElements(By.tagName("a"));
String[] linkTexts = new String[linkElements.size()];
driver.manage().timeouts().implicitlyWait(20, TimeUnit.MINUTES);
int j = 0;
for (WebElement e : linkElements) {
linkTexts[j] = e.getText();
j++;
}
// test each link
for (String t : linkTexts) {
if (t != null && !t.isEmpty()) {
driver.findElement(By.linkText(t)).click();
String title;
title = driver.getTitle();
System.out.println("title is"+title);
if((title.contains("You are not authorized to view this page"))||(title.contains("404")) ||
(title.contains("408"))|| (title.contains("400")) || (title.contains("401"))
|| (title.contains("403"))||(title.contains("Page not found"))||(title.contains("500"))||(title.contains("error"))||(title.contains("503 Service Unavailable")))
{
System.out.println(t + " the link is not working");
} else {
System.out.println("\"" + t + "\"" + " is working.");
driver.navigate().back();
}
}
}driver.quit();
}
}
}
Instead of getting link text(s) and clicking, you can just retrieve the "href" attribute of each "a" tag elements. Since the purpose is just to navigate to each url and check the links by opening and getting title, I recommend this as the better way. Below is the updated code, that worked.
Note: I have just tweaked the existing code for solving it
#Test
public void findurl() throws Throwable, IOException {
FileInputStream fi = new FileInputStream("D:\\sites.xls");
Workbook wb = Workbook.getWorkbook(fi);
//driver = new FirefoxDriver();
Sheet s = wb.getSheet(0);
System.out.println("Program Started"+s.getName());
System.out.println(s.getRows());
for (int row = 0; row < s.getRows(); row++)
{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
String Urllist = s.getCell(0, row).getContents().toString();
System.out.println("Url number "+(row+1)+": " + Urllist);
driver.get(Urllist);
List<WebElement> linkElements = driver.findElements(By.tagName("a"));
System.out.println("The number of links under URL number "+(row+1)+" is: "+linkElements.size());
String[] linkhrefs = new String[linkElements.size()];
int j = 0;
for (WebElement e : linkElements) {
linkhrefs[j] = e.getAttribute("href");
j++;
}
// test each link
int k=0;
for (String t : linkhrefs) {
try{
if (t != null && !t.isEmpty()) {
System.out.println("Navigating to link number "+(++k)+": '"+t+"'");
driver.navigate().to(t);
String title;
title = driver.getTitle();
System.out.println("title is: "+title);
if((title.contains("You are not authorized to view this page"))||(title.contains("404")) ||
(title.contains("408"))|| (title.contains("400")) || (title.contains("401"))
|| (title.contains("403"))||(title.contains("Page not found"))||(title.contains("500"))||(title.contains("error"))||(title.contains("503 Service Unavailable")))
{
System.err.println(t + " the link is not working because title is: "+title);
} else {
System.out.println("\"" + t + "\"" + " is working.");
//driver.navigate().back();
}
}else{
System.err.println("Link's href is null.");
}
}catch(Throwable e){
System.err.println("Error came while navigating to link: "+t);
}
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
System.out.println("-------------------------------------------------------------");
System.out.println("Closing the driver as the links under url: "+Urllist+" have been checked out");
driver.quit();
}
}