How to store a webtable in arraylist then verify the data in selenium webdriver - selenium

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");
}
}

Related

Selenium, clicking a button and secound iteration of a loop failing

I have a test
public class SeleniumForh extends BaseTest {
private static List<String> FNR;
private static final int THREAD_COUNT = 1;
private static Set<String> THREADS = Collections.synchronizedSet(new HashSet<String>());
static {
List<String> fnr = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(SeleniumManntallskryss.class.getResourceAsStream("/fnr")));
String line;
while ((line = reader.readLine()) != null) {
fnr.add(line);
}
FNR = Collections.synchronizedList(fnr);
} catch (IOException e) {
e.printStackTrace();
}
}
public SeleniumForhandstemmer(String platform, String browserName, String browserVersion) {
super(platform, browserName, browserVersion);
}
#Parameterized.Parameters
public static LinkedList<String[]> getEnvironments() throws Exception {
LinkedList<String[]> env = new LinkedList<String[]>();
for (int i = 0; i <THREAD_COUNT; i++) {
env.add(new String[]{"ANY", "firefox", "35"});
}
return env;
}
#Test
public void testForhand() throws Exception {
try {
System.out.println(System.currentTimeMillis() + " - " + Thread.currentThread() + ": testForhand");
THREADS.add(Thread.currentThread().toString());
do {
System.out.println(System.currentTimeMillis() + " - " + Thread.currentThread() + ": THREADS.size() = " + THREADS.size());
Thread.sleep(5000);
} while (THREADS.size() < THREAD_COUNT);
System.out.println(System.currentTimeMillis() + " - " + Thread.currentThread() + ": testForhand - ready to run");
WebDriver driver = webDriverThreadLocal.get();
driver.get("https://kill");
Assert.assertTrue(driver.getTitle().equals("Ehh"));
WebElement element = driver.findElement(By.xpath("/html/body/div/div[3]/div/div[2]/div/div/div/a"));
element.click();
WebElement brukerid = driver.findElement(By.xpath("/html/body/form/input[1]"));
brukerid.clear();
brukerid.sendKeys(new CharSequence[]{"2333"});
WebElement logginnknapp = driver.findElement(By.cssSelector("input[value=\"Login\"]"));
logginnknapp.click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement rolle = driver.findElement(By.cssSelector("#event33"));
rolle.click();
for (int i = 0; i < 10; i++) {
System.out.println("Re nr " + (i + 1));
WebElement fo = driver.findElement(By.linkText("Ree"));
fo.click();
WebElement sted = driver.findElement(By.xpath("//*[#id=\"form:panel:tabell_dd_data\"]/tr[1]/td"));
sted.click();
takeScreenshot("nod");
WebElement velg = driver.findElement(By.xpath("//*[#id=\"form:panel:tabeller\"]/div/div[2]"));
velg.click();
WebElement fnrFane = driver.findElement(By.xpath("//*[#id=\"mand:manntallsSokForm:tabView\"]/ul/li[2]"));
fnrFane.click();
WebElement velger = driver.findElement(By.xpath("//input[#data-aft=\"fodselsnummer\"]"));
velger.clear();
String fnr = FNR.remove(0);
velger.sendKeys(fnr);
WebElement sokknapp = driver.findElement(By.xpath("//*[#id=\"mad:tabView:searchSSN\"]"));
sokknapp.click();
Thread.sleep(10000);
WebElement fnrTxt = driver.findElement(By.xpath("//*[contains(text(), '" + fnr + "')]"));
System.out.println("Fnr tekstelement: " + fnrTxt);
WebElement regStemme = driver.findElement(By.xpath("//*[#id=\"stemmegivning:form:markOffAdvance\"]"));
System.out.println("Knd: " + regStemme);
regStemme.click();
driver.findElement(By.xpath("//*[contains(text(), 'bd')]"));
driver.get("https://y");
driver.findElement(By.xpath("//*[contains(text(), 'Min side')]"));
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
System.out.println(System.currentTimeMillis() + " - " + Thread.currentThread() + ": testSimple - test finished");
}
}
}
The problem is that when running the secound iteratoion the button I want to click is just marked with a square around it in the running browser, not cliked. This happens everu time on the second (not the first iteration), I have tried sleep between iterations and have also confirmed that the button i sfound, so the problem is the click function. And I can see it tries to click because a square is apperaring around the buttoon.

how to get text from span in the below code

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++;
}
}
}
}

Required element cannot be clicked as another element is overlapping, tried the scroll code as well

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.

I have not getting clear result about this issue

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();
}
}

Output values from selenium webdriver to excel sheet

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