I want to paginate through a table using selenium in java - java

I need your help I want to paginate through a table an store the values of it untill "Next Button" disables.
Although storing values is not ossible its ok. But help me in pagination I want to click on the button it the next button untill it is not disabled .Please help me. I am on a internship
Java Code:
package Onsight.Framework;
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 org.openqa.selenium.chrome.ChromeOptions;
import com.github.javafaker.Faker;
import avdhut.onsight.commonutils.BaseComponenets;
import avdhut.onsight.pageobject.HomePage;
import avdhut.onsight.pageobject.LoginPage;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Webtable extends BaseComponenets {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String urlString = "https://oinsightsvm1.westindia.cloudapp.azure.com:444/ctsOInsightsBMS/res/createReport.html";
String userEmailString = "User66";
String userPassword = "Avdhut#5201";
String titleString;
String textString="Clarita";
Faker faker = new Faker();
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
// options.addArguments("--ignore-ssl- errors=yes");
options.addArguments("--ignore-certificate-errors");
WebDriver driver = new ChromeDriver(options);
driver.get(urlString);
LoginPage loginPage = new LoginPage(driver);
loginPage.login_username(userEmailString);
loginPage.click0nsubmit();
loginPage.EnterPassword(userPassword);
loginPage.click0nsubmit();
HomePage homePage = new HomePage(driver);
// homePage.view_report_values(textString);
IsVisible(baseTableBy);
WebElement baseTable=driver.findElement(baseTableBy);
List<WebElement> table_roWebElement=baseTable.findElements(report_name_rowsBy);
for (WebElement webElement : table_roWebElement) {
if (webElement.getText().contains(report_title)) {
System.out.println(true);
IsClickable(viewBy);
System.out.println(webElement.getText());
webElement.findElement(viewBy).click();
IsClickable(view_dataBy);
driver.findElement(view_dataBy).click();
while (IsVisible(paginateBy)) {
IsClickable(paginateBy);
driver.findElement(paginateBy).click();
}
} else {
}
}
}
//tr[class='odd'] em[class='fa fa-table']
Html:

After logging in, once you reach the table which contains the list of reports, add the below code and try:
Thread.sleep(2000);
// to close the toast message, if the toast message does not appear, comment the below line
driver.findElement(By.xpath(".//button[#class='toast-close-button']")).click();
boolean flag = true;
// below while loop will click the 'NEXT' button until it is disabled
while (flag) {
WebElement nextBtn = driver.findElement(By.id("query-table_next"));
if (!nextBtn.getAttribute("class").contains("disabled")) {
nextBtn.click();
Thread.sleep(1000);
} else {
flag = false;
System.out.println("In the last page");
}
}

Related

My Xpath is correct & no iFrame and I can locate element in Chrome console but my program still fails. I have used explicit wait also

My Xpath is correct & no iFrame and I can locate element in Chrome console but my program still fails. I have used explicit wait also.
Website: https://qrgo.page.link/8YEcD I am trying to locate the male gender radio button.
I can locate the element in the same chromedriver console but still it shows no element found exception.
Code:-
package automation;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class residence {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", ".\\lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://serviceonline.bihar.gov.in/resources/homePage/10/loginEnglish.htm");
driver.findElement(By.xpath("//label[contains(text(),'General')]")).click();
driver.findElement(By.xpath(("//p[contains(text(),'Residential')]"))).click();
driver.findElement(By.xpath(("//div[#id='collapseOneOne']/div/p/a"))).click();
/* Write Gender accordingly.Default is Male(M).(F) and (T)*/
char gender='M';
WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='17290_1']")));
if(gender=='M')
{
driver.findElement(By.xpath("//input[#id='17290_1']")).click();
}
else if(gender=='F')
{
driver.findElement(By.xpath("//input[#id='17290_2']")).click();
}
else
{
driver.findElement(By.xpath("//input[#id='17290_3']")).click();
}
}
}
Here is a screenshot of the chrome window in which the testcase run:
Here also u can see that element is visible
Error message image
When click on the link, it is opening a new tab, you need to switch to new tab before accessing the element.
package automation;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class residence {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", ".\\lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://serviceonline.bihar.gov.in/resources/homePage/10/loginEnglish.htm");
// Store the current window handle
String parent_handle = driver.getWindowHandle();
driver.findElement(By.xpath("//label[contains(text(),'General')]")).click();
driver.findElement(By.xpath(("//p[contains(text(),'Residential')]"))).click();
driver.findElement(By.xpath(("//div[#id='collapseOneOne']/div/p/a"))).click();
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
if(!parent_handle.equals(winHandle))
{
driver.switchTo().window(winHandle);
}
}
/* Write Gender accordingly.Default is Male(M).(F) and (T)*/
char gender='M';
WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(30));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//label[#for='17290_1']")));
if(gender=='M')
{
driver.findElement(By.xpath("//label[#for='17290_1']")).click();
}
else if(gender=='F')
{
driver.findElement(By.xpath("//label[#for='17290_2']")).click();
}
else
{
driver.findElement(By.xpath("//label[#for='17290_3']")).click();
}
}
}

Selenium - Clicking Submit button is not navigating to next page

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class voot {
public static void main(String[] args) {
// TODO Auto-generated method stub
//WebDriver driver = new SafariDriver();
System.setProperty("webdriver.chrome.driver", "/Users/dkurugod/Desktop/selenium_tutorials/chromedriver");
WebDriver driver = new ChromeDriver();
String URL = "https://voting.voot.com/vote/";
driver.get(URL);
String title = driver.getTitle();
System.out.println(title);
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
WebElement name = driver.findElement(By.xpath("//img[contains(#alt,'Harry')]"));
name.click();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
WebElement submit = driver.findElement(By.xpath("//button[normalize-space()='Submit']"));
submit.click();
}}
<button class="jss190"> Submit</button>
After clicking on Submit button, it is not navigating to the next page. Can someone please suggest to me how to proceed with this. I am still a beginner in Selenium. Thanks
1 You do not need to use this twice:
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
2 For submit button try the following xpath locator:
//button[contains(#class,'jss190')]
Or this:
//button[contains(text(),'Submit')]
The second locator will only work when there in only one button with type submit.

How to make sure I am checking the checkboxes that are unchecked selenium java

My below code does not work. Already checked checkboxes are getting unchecked when I run below code.
Need your suggestions.
'''
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.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DropboxSelect {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver(); // launch chrome
driver.manage().window().maximize(); // maximize window
driver.manage().deleteAllCookies(); // delete all the
cookies
// dynamic wait
driver.manage().timeouts().pageLoadTimeout(40,
TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
driver.get("https://www.jquery-az.com/boots/demo.php?
ex=63.0_2"); // enter URL
driver.findElement(By.xpath("//button[contains(#class,'multiselect')]")).click();
List<WebElement> list =
driver.findElements(By.xpath("//ul[contains(#class,'multiselect-
container')]//li//a//label"));
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getText());
if (!list.get(i).isSelected()) {
list.get(i).click();
}
}
'''
You could adapt the xpath for your list and the condition if an item is selected as follows:
List<WebElement> list = driver
.findElements(By.xpath("//ul[contains(#class,'multiselect-container')]//li"));
for (WebElement webElement : list) {
System.out.println(webElement.getText());
if (!"active".equals(webElement.getAttribute("class"))) {
webElement.click();
}
}
It works but it is a bit brittle.

Selenium Webdriver - Java, Browser shows message "ERROR: This page has expired. Please cancel this operation and try again" on button click

When I run the test method runSuite(), everything is fine till the last line of the method:
button.click(); // clicks the button on page
The above statement results in the page expired issue.
I get the following message on the browser window:
ERROR: This page has expired. Please cancel this operation and try again.
I tried playing around browser cache, but that didn't help.
package com.swtestacademy.webdriver;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Timeouts;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.*;
import com.util.MockLoginClient;
import static org.junit.Assert.*;
public class MainTest {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
MockLoginClient.instance().authenticateAsHcrCaseWorker();
//System.setProperty("webdriver.ie.driver","C:/IEDriverServer_x64_3.4.0/IEDriverServer.exe");
//driver = new InternetExplorerDriver();
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
options.addPreference("log", "{level: trace}");
capabilities.setCapability("marionette", true);
capabilities.setCapability("moz:firefoxOptions", options);
capabilities.setCapability(CapabilityType.ELEMENT_SCROLL_BEHAVIOR, 1);
capabilities.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, "applicationCacheEnabled");
System.setProperty("webdriver.gecko.driver", "C:/geckodriver-v0.16.1-win64/geckodriver.exe");
//ProfilesIni profile = new ProfilesIni();
//profile.getProfile("default");
FirefoxProfile ffprofile = new FirefoxProfile();
ffprofile.setPreference("browser.cache.disk.enable", true);
ffprofile.setPreference("browser.cache.memory.enable", true);
ffprofile.setPreference("browser.cache.offline.enable", true);
ffprofile.setPreference("network.http.use-cache", true);
driver = new FirefoxDriver(capabilities);//ffprofile);
//driver.manage().deleteAllCookies();
baseUrl = "http://localhost:8082/";
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.MILLISECONDS);
//driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);
// driver.manage().timeouts().setScriptTimeout(3000,TimeUnit.MILLISECONDS);
driver.get(baseUrl + "/Curam/AppController.do");
}
#Test
public void test() throws Exception {
driver.get(baseUrl + "/Curam/AppController.do");
driver.findElement(By.id("app-sections-container-dc_tablist_DefaultAppSection-sbc_tabLabel")).click();
driver.findElement(By.cssSelector("div.dojoxExpandoIcon.dojoxExpandoIconLeft")).click();
Thread.sleep(1000);
driver.findElement(By.id("dijit_layout_AccordionPane_1_button_title")).click();
driver.findElement(By.cssSelector("#dijit_layout_AccordionPane_1 > ul > li > a.curam-content-pane-single-link")).click();
driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
iterator.next();
}
//driver.switchTo().window(subWindowHandler); // switch to popup window
driver.findElement(By.id("curam_ModalDialog_0"));
driver.findElement(By.className("dijitDialogPaneContent"));
driver.findElement(By.id("curam_ModalUIMController_0"));
driver.findElement(By.className("contentPanelFrameWrapper"));
driver.switchTo().frame("iframe-curam_ModalDialog_0");
driver.findElement(By.tagName("html"));
driver.findElement(By.tagName("body"));
driver.findElement(By.id("content"));
driver.findElement(By.id("mainForm"));
driver.findElement(By.id("modal-actions-panel"));
// driver.findElement(By.xpath("//div[#id='modal-actions-panel']/div[2]/a/span/span/span")).click();
WebElement nxtBtn = driver.findElement(By.id("__o3btn.NEXTPAGE_2"));
Thread.sleep(1000);
nxtBtn.click();
driver.findElement(By.xpath("//div[#id='modal-actions-panel']/div[2]/a[2]/span/span/span")).click();
driver.findElement(By.id("__o3btn.SAVE_0")).click();
}
#After
public void tearDown() throws Exception {
//driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
#Test
public void runSuite() throws InterruptedException {
System.out.println(driver);
WebElement xy = driver.findElement(By.id("app-sections-container-dc_tablist_DefaultAppSection-sbc_tabLabel"));
xy.click();
driver.findElement(By.cssSelector("div.dojoxExpandoIcon.dojoxExpandoIconLeft")).click();
WebElement personSearchLink = driver.findElement(By.linkText("Person…"));
Thread.sleep(1000);
personSearchLink.click();
WebElement appStc = driver.findElement(By.id("DefaultAppSection-stc"));
WebElement djtTab = appStc.findElement(By.className("dijitTabPaneWrapper"));
Thread.sleep(1000);
WebElement tpChldWrapper = djtTab.findElement(By.className("dijitTabContainerTopChildWrapper"));
WebElement lyoutCntntPane = tpChldWrapper.findElement(By.id("dojox_layout_ContentPane_1"));
WebElement tbWrpr = lyoutCntntPane.findElement(By.className("tab-wrapper"));
WebElement noDtlsPnl = tbWrpr.findElement(By.className("no-details-panel"));
WebElement cntntAreaCntnr = noDtlsPnl.findElement(By.className("content-area-container"));
WebElement fstUIMCntrlr = cntntAreaCntnr.findElement(By.id("curam_FastUIMController_1"));
WebElement cntntPnlFrmWrpr = fstUIMCntrlr.findElement(By.className("contentPanelFrameWrapper"));
WebElement iFrameElmnt = cntntPnlFrmWrpr.findElement(By.tagName("iframe"));
driver.switchTo().frame(iFrameElmnt);
WebElement inputText = driver.findElement(By.id("__o3id0"));
Thread.sleep(100);
inputText.sendKeys("24684");
// Thread.sleep(4000);
WebElement button = driver.findElement(By.linkText("Search"));
button.click();
}
}
I could see the issue. This behavior is seen for Firefox and Internet explorer only and not for chrome.
The solution would be to check the default desired capabilities for Chrome driver and set the same for Firefox driver or IE driver.
Easier Solution: Switch to Chrome Driver.

how to locate an element of a page after new data loaded on the same page in selenium webdriver

I am trying to copy the table data of the html page which is loaded on the same page after clicking on the 'Get Table' button on the previous page. However, as the page url is not changing I am getting exception of 'No such element' when trying to locate new elements on newly loaded page. Following is the code I tried:
package com.test.selenium;
import java.util.List;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
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;
import junit.framework.Test;
import junit.framework.TestSuite;
public class Example1{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Java Stuff\\Selenium Tutorial\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.oanda.com/currency/table");
WebElement date = driver.findElement(By.name("date"));
date.sendKeys("12/04/10");
WebElement date_frmt = driver.findElement(By.name("date_fmt"));
date_frmt.sendKeys("yy/mm/dd");
WebElement curr = driver.findElement(By.name("exch"));
curr.sendKeys("US Dollar.USD");
Select sel = new Select(driver.findElement(By.name("Currency")));
sel.deselectAll();
List lsize = sel.getOptions();
int count = lsize.size();
for(int j=0;j<count;j++)
{
String lvalue = sel.getOptions().get(j).getText();
sel.selectByVisibleText(lvalue);
}
WebElement crr = driver.findElement(By.name("dest"));
crr.click();
driver.getCurrentUrl();
String table = driver.findElement(By.id("converter_table")).getText();
System.out.println(table);
}
}
According to exception it seems that element not exists on the page, or smth wrong with you xpath. Why you use xpath?! Try css selectors (they are more powerful and stable) =) e.g.
driver.findElement(By.css("#converter_table"));
P.S. if you want to verify that your selector is correct (no matter xpath or css) use dev console in browser (e.g. for css enter $("#converter_table") in console, and if element exists (and this id has no type in the name) then you'll see what this selector will return)). For xpath use $x("xpath")
UPDATE:
Simple solution i think is to add some method which will wait for element, some period of time. Below sample code in C# (test with wait method)
private IWebDriver driver;
[SetUp]
public void SetUp()
{
// Here i just create browser as you (firefox, chrome etc);
driver = CreateBrowser("http://www.oanda.com/currency/table");
}
[TearDown]
public void TearDown()
{
driver.Dispose();
}
[Test]
public void PortTest()
{
var dateElement = driver.FindElement(By.Name("date"));
dateElement.SendKeys("12/04/10");
var dateFrmt = driver.FindElement(By.Name("date_fmt"));
dateFrmt.SendKeys("yy/mm/dd");
var curr = driver.FindElement(By.Name("exch"));
curr.SendKeys("US Dollar.USD");
var crr = driver.FindElement(By.Name("dest"));
crr.Click();
WaitUntilLoad();
var table = driver.FindElement(By.Id("converter_table"));
Console.Write("the text is " + table.Text);
}
public void WaitUntilLoad()
{
int repetitionCount = 0;
bool isLoaded = false;
while (!isLoaded)
{
var table = driver.FindElements(By.Id("converter_table")).Count;
if (table > 0 )
isLoaded = true;
Thread.Sleep(250);
repetitionCount++;
Console.WriteLine("Searching again for element");
if (repetitionCount > 25) break;
}
}
you get NoSuchElement because your xpath seems wrong
try
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//*[#id='content_section']/table")));
String table = driver.findElement(By.xpath(".//*[#id='content_section']/table")).getText();

Categories