I am trying to login and search records based on date selected from a calendar. I have used try catch exception after each step. I need to replace try catch with WebDriverWait. But the problem is that I have fields on the page which are getting identified by id or XPath. So I am not getting a way out how to implement WebDriverWait instead of try catch. Can anyone help me out? Below is my code structure with details.
public class Login {
public static WebDriver driver;
String username = "username";
String password = "password";
String baseurl = "http://mybusiness.com/login.aspx";
public class Details {
#Test(priority = 0)
public void loginpage() {
//WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.chrome.driver","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
capabilities.setCapability("chrome.binary","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get(baseurl);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement password = driver.findElement(By.id("Password"));
password.sendKeys(password);
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement button = driver.findElement(By.id("ButtonClick"));
button.click();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
// Selecting a date from date picker
#Test(priority = 1)
public void RecordSearch() {
WebElement calendar = driver.findElement(By.id("CalendarId"));
calendar.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement month = driver.findElement(By.xpath("XPath"));
month.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement day = driver.findElement(By.xpath("XPath"));
day.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement submit = driver.findElement(By.id("Submit"));
submit.click();
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
driver.close();
}
I would have thought you'd be better off adding an implicit wait, e.g. once you've setup your driver object add the following line:
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
A simple example would take your code
try
{
Thread.sleep(10000); // 1000 milliseconds is one second.
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
and change it to
String username = "username123";
WebDriverWait wait = new WebDriverWait(driver, 10); // 10 seconds
WebElement usernameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("UserName")));
usernameField.sendKeys(username);
Once you have defined wait, you can reuse it over and over and it will have the same attributes, e.g. 10 sec wait time.
String password = "abc123";
WebElement passwordField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Password")));
passwordField.sendKeys(password);
NOTE: I noticed that you were using username.sendKeys(username);. I'm assuming/hoping this isn't actual code since .sendKeys() takes a String and you have username defined as a WebElement. I fixed it in my code and named the two differently.
There is WebDriverWait functionality in selenium, you can set explicit wait. You are using selenium webdriver, then it is far better to use WebDriverWait for waiting purpose to element. follow below code
protected WebElement waitForPresent(final String locator, long timeout) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement ele = null;
try {
ele = wait.until(ExpectedConditions
.presenceOfElementLocated(locator));
} catch (Exception e) {
throw e;
}
return ele;
}
protected WebElement waitForNotPresent(final String locator, long timeout) {
timeout = timeout * 1000;
long startTime = System.currentTimeMillis();
WebElement ele = null;
while ((System.currentTimeMillis() - startTime) < timeout) {
try {
ele = findElement(locator);
Thread.sleep(1000);
} catch (Exception e) {
break;
}
}
return ele;
}
Whenever you require wait for element present, call waitForPresent method with expected parameters.
If you explore little, you can find different types of WebDriverWait. One of the most common is WebDriver.wait(timeinmilliseconds).
and for example, others are,
webDriver.waituntil (Expectedconditions)...
wait.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
WebElement button = driver.findElement(By.className("sel"));
String enabled = button.getText();
return enabled.contains(city);
}
});
or for example
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("froexample_username_txtbox")));
PS : define private final WebDriverWait wait;
It may be more useful if you are not sure about implict timewait value.(be being specific about events and results)
Related
I have code something like this
WebDriver driver = new FirefoxDriver();
driver.get(something URL);
WebDriverWait waiting = new WebDriverWait(driver, 10, 1000);
WebElement element = waiting.until(ExpectedConditions.presenceOfElementLocated(By.id(my_id)));//problem is here
But then i try to find element on my page, WebDriverWait waiting until the page has completely loaded and then starts searching.
If I'm trying something like this
WebDriverWait waiting = new WebDriverWait(driver, 10, 2700);
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
WebElement element;
try {
driver.get(something_url);
} catch (TimeoutException e) {
((JavascriptExecutor) driver).executeScript("window.stop();");
}finally {
element = waiting.until(ExpectedConditions.presenceOfElementLocated(By.id(my_id)));
}
It works, but if I go on like this
element.click();//go to another page
On this line doesn't throw a timeout exception, I have to wait for the full page load.
How to be in this situation ?
Solution is to wait for ajax refresh to complete on this page:
public void waitForAjaxRefresh() {
System.out.println("Waiting for Ajax Refresh");
try {
WebDriverWait wait = new WebDriverWait(driver,35);
final JavascriptExecutor javascript = (JavascriptExecutor) (driver instanceof JavascriptExecutor ? driver
: null);
wait.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver d) {
boolean outcome = Boolean.parseBoolean(javascript
.executeScript("return jQuery.active == 0")
.toString());
return outcome;
}
});
} catch (TimeoutException ex) {
throw new TimeoutException("Timed out after "
+ 35
+ " seconds while waiting for Ajax to complete.");
} catch (WebDriverException e) {
System.out.println("JQuery libraries are not present on page "
+ driver.getCurrentUrl() + " - "
+ driver.getTitle());
}
}
I'm trying to expand all comments, replies, see more in comment, and see more in post in Facebook.
1) The codes I have written below allows me to expand all contents that I want except for maybe a few replies in a post even though I have put the repliesbutton in a loop.
2) There will a Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with error at the .click() if there is no try-catch in all the smaller for loops.
//declare WebDriverWait variable, times out after 20 seconds
WebDriverWait wait = new WebDriverWait(dr, 20);
//check element is present on the DOM of a page and visible
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("commentable_item")));
List<WebElement> comments = dr.findElements(By.className("commentable_item")); //get the comments
//iterate through the comments
for (WebElement comment : comments) {
boolean clickMore = true;
try {
while(clickMore == true) {
//find web elements by their respective class name
List<WebElement> commentsbutton = comment.findElements(By.className("UFIPagerLink")); //view more/previous comments
List<WebElement> repliesbutton = comment.findElements(By.className("UFIPagerIcon")); //replies
List<WebElement> seemorebutton = comment.findElements(By.className("_5v47")); //see more in comment
List<WebElement> seemorelinkbutton = dr.findElements(By.className("see_more_link")); //see more in link
//click more comments
if(commentsbutton.size() > 0) {
for (WebElement comments_element : commentsbutton) {
//comments_element.click(); //click on button if found
//Thread.sleep(5000); //pause for 5 seconds
try{
comments_element.click(); //click on button if found
Thread.sleep(5000); //pause for 5 seconds
} catch(Exception e){
}
}
for (WebElement replies_element : repliesbutton) {
//replies_element.click(); //click on button if found
//Thread.sleep(3000); //pause for 3 seconds
try{
replies_element.click(); //click on button if found
Thread.sleep(3000); //pause for 5 seconds
} catch(Exception e){
}
}
}
else clickMore = false;
for (WebElement seemorelinks_element : seemorelinkbutton) {
try{
seemorelinks_element.click(); //click on button if found
Thread.sleep(5000); //pause for 5 seconds
} catch(Exception e){
}
}
for (WebElement seemore_element : seemorebutton) {
try{
seemore_element.click(); //click on button if found
Thread.sleep(5000); //pause for 5 seconds
} catch(Exception e){
}
}
}
} catch (NoSuchElementException e) { //when no elements are found
System.out.println("Comments in this post not found");
}
}
}
//return the given element if it is visible and has non-zero size, otherwise null.
private static WebElement elementIfVisible(WebElement element) {
return element.isDisplayed() ? element : null;
}
public static ExpectedCondition<WebElement> visibilityOfElementLocated(final By locator) {
return new ExpectedCondition<WebElement>() {
#Override
public WebElement apply(WebDriver driver) {
try {
return elementIfVisible(dr.findElement(locator));
} catch (StaleElementReferenceException e) {
return null;
}
}
};
}
}
You can create a utility method and put it in some 'Utility.java' class something like below:
public void click(WebElement element)
{
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
if(element.isDisplayed())
element.click();
}
Usage:
WebElement element=driver.findElement(//Locator);
Utility.click(element);
This will ensure every time before you click the element is scrolledIntoView.
Let me know if you need further help on this.
There is a table list of username, from these table I have edited the username "Pra" to "Pra1", but now when I come to the user table list its not finding a user with the name "Pra" because its updated with "Pra1".
So, what I want is after updating an username in the search filter it search with updated username (With "Pra1").
Below are the running code upto the updated username please help me after that:
public class InsSystemCenter {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("URL");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Verify the insfocus system center page has been opened or not by
// xpath//
if (driver.findElement(By.xpath("/html/body/table/tbody/tr[1]/td/h1")) != null) {
System.out.println("Center has been opened");
} else {
System.out.println("Center is not displaying");
}
WebElement userName = driver.findElement(By.name("username"));
userName.sendKeys("pra");
WebElement password = driver.findElement(By.name("password"));
password.sendKeys("123456");
WebElement signIn = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[2]/td/table/tbody/tr[1]/td/form/center/div/table/tbody/tr[4]/td/input"));
signIn.click();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Verify that welcome page is displayed or not//
WebElement welcomePageVerify = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[3]/td/table/tbody/tr[1]/td/div[2]/span"));
if (welcomePageVerify.isDisplayed()) {
System.out.println("Welcome page is displaying");
} else {
System.out.println("Welcome page is not displaying");
}
// Try to click on the tab name "Settings" by xpath//
WebElement settings = driver.findElement(By
.xpath("/html/body/table/tbody/tr[2]/td/ul/li[3]/a"));
settings.click();
// Verifying that after clicking on "Setting" it opens a database page
// or not//
WebElement settingsVerify = driver
.findElement(By
.xpath("/html/body/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]/h1/span"));
if (settingsVerify.isDisplayed()) {
System.out
.println("Database page is displayed after clicking on Setting tab");
} else {
System.out.println("Database page is not displaying");
}
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
// Click on the button "Users" by xpath, so that it goes to the page
// where it show the list of users //
WebElement users = driver
.findElement(By
.xpath("/html/body/form/table/tbody/tr[3]/td/table/tbody/tr[1]/td[1]/p/a[2]"));
users.click();
// Verifying for users page opened or not//
WebElement usersPageVerify = driver
.findElement(By
.xpath("/html/body/table/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/div/table/tbody/tr/td[2]/h1"));
if (usersPageVerify.isDisplayed()) {
System.out
.println("Users page is displayed after clicking on users button");
} else {
System.out.println("Users page is not displaying");
}
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
System.out.println("Total time take " + new Date());
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
System.out.println("Total time take " + new Date());
WebElement usUserName = driver.findElement(By.id("g_UserName"));
usUserName.sendKeys("Pra");
usUserName.sendKeys(Keys.ENTER);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
usUserName.sendKeys(Keys.TAB);
System.out.println("Total time take " + new Date());
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
// Checked the checkbox of find elemet or user//
WebElement checkbox = driver.findElement(By.id("jqg_tblMainTable_243"));
checkbox.click();
// After checked the checkbox it enables the edit button for edit the
// user//
WebElement editButton = driver.findElement(By.id("btnEdit"));
editButton.click();
// ------------Edit user popup--------------//
// Verify edit popup opened or not//
String source = driver.getPageSource();
int a = source.indexOf("Edit User:");
if (a > 0) {
System.out.println("Edit user popup is displayed");
} else {
System.out.println("Edit user popup is not displaying");
}
// All the WebElement parameter is located here//
WebElement euUserName = driver.findElement(By.id("UserName"));
euUserName.clear();
euUserName.sendKeys("pra1");
WebElement euFullName = driver.findElement(By.id("txtFullName"));
euFullName.clear();
euFullName.sendKeys("pra1");
WebElement euPassword = driver.findElement(By.id("txtPassword"));
euPassword.sendKeys("123456");
WebElement euConfirmPassword = driver.findElement(By
.id("txtConfirmPassword"));
euConfirmPassword.sendKeys("123456");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Error in wait");
}
WebElement dropdown = driver.findElement(By.id("RoleID"));
// Verify dropdown is displayed or not not //
if (dropdown.findElement(By.id("RoleID")) != null) {
System.out.println("Dropdown is displayed");
} else {
System.out.println("Dropdown is not displaying");
}
Select clickThis = new Select(dropdown);
clickThis.selectByVisibleText("Normal");
System.out.println("Drop down values "+clickThis.getOptions().get(0).getText());
WebElement euUserDetail = driver.findElement(By.id("UserDetails"));
euUserDetail.clear();
euUserDetail.sendKeys("pra1");
WebElement euOk= driver.findElement(By.xpath("/html/body/div[3]/div[3]/div/button[1]"));
euOk.click();
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
driver.quit();
}
}
Just call clear() method before your calling sendKeys("your text").
This should work.
Just use the clear function before passing the value to the webelement
WebElement userName = driver.findElement(By.name("username"));
userName.clear();
userName.sendKeys("pra");
Same way you can use for all the elements.
ok i can't even be bothered trying to read a 7 million line long main method
1) refactor it in to separate logical methods (responsibility driven design)
2) when you have done that post us the code responsible for your issues
3) maybe look at assigning the value you want to search on to a temporary variable so you can find it again?
I am Trying to Automate a Test sequence of Login - Booking - Cancellation.
Till Booking its Fine , But moment it Reaches Cancellation, It throws a java lang Null-Pointer Exp.
I rechecked and My locators(xpath) is correct(xpath-Checker) and I am Trying to getText() the Ticket Number and proceed to cancellation.
Problem is whenever WebDriver is reaching the Booking confirmation Page , which Loads after a While, it Fails and Returns Null Pointer Exp..
It may be a Loading Issue which is handled or I am messed up with my Java Concept...
Please Help !! anyone...
public class StackOverflow {
public static WebDriver driver;
public static Properties p;
public static FileInputStream f ;
#Test
public void loginTest() {
System.out.println("Enter Login");
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver = new FirefoxDriver();
driver.get("https://in3.seatseller.travel/");
driver.manage().window().maximize();
try{
driver.findElement(By.name(p.getProperty("login.username.textfield"))).sendKeys("UserName");
driver.findElement(By.name(p.getProperty("login.password.textfield"))).sendKeys("Password");
WebElement ele =driver.findElement(By.id(p.getProperty("login.signin.button")));
ele.click();
}
catch (Exception e) {
}
}
#Test (dependsOnMethods={"loginTest"})
public void booking() throws InterruptedException{
System.out.println("Enter Booking");
// Type Bangalore on Source Field..
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebDriverWait wait2 = new WebDriverWait(driver, 30);
wait2.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(p.getProperty("oneapp.source.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys("Bangalore");
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys(Keys.TAB);
Thread.sleep(900L);
// Type Mysore on Destination Field
WebDriverWait wait1 = new WebDriverWait(driver, 30);
wait1.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.destination.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.destination.textfield"))).sendKeys("Tirupathi");
driver.findElement(By.xpath(p.getProperty("oneapp.destination.textfield"))).sendKeys(Keys.TAB);
}
#Test (dependsOnMethods={"booking"})
public void cancellation() throws InterruptedException{
System.out.println("Enter Cancellation");
WebDriverWait wait4 = new WebDriverWait(driver, 60);
Thread.sleep(9000);
/*Facing Null Pointer Exp Here */
wait4.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(p.getProperty("oneapp.congratulations.text"))));
wait4.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.congratulations.text"))));
Thread.sleep(9000);
/*Facing Null Pointer Exp Here */
WebElement ticket =driver.findElement(By.xpath(p.getProperty("oneapp.ticket.text")));
/*Want to getText() Ticket Number to cancel*/
String ticket1 = ticket.getText();
System.out.println(ticket1);
driver.findElement(By.xpath(p.getProperty("oneapp.leftNavCancel.link "))).click();
WebDriverWait wait1 = new WebDriverWait(driver, 30);
wait1.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.phoneNumber.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.phoneNumber.textfield"))).sendKeys(TIN1);
driver.findElement(By.xpath(p.getProperty("oneapp.search.button"))).click();
driver.findElement(By.xpath(p.getProperty("oneapp.cancel.button"))).click();
}
}
Either add Properties p=new Properties(); in your cancellation() method or mention it outside of the test methods(In the begining, you've declared public static Properties p; rather define it there like public static Properties p = new Properties();)
In first two methods you create f = new FileInputStream but in the third method you read properties without it. Did you try to read properties again?
Can any one pls help me out
There are many check boxes available with values and I have to choose a particular value in check box. I dont know how to choose a check box value in selenium webdriver
https://www.blueshieldca.com/fap/app/search.html
This one works.. This will click the check box "General Medicine" under "Type" on left menu...
public class SampleUITest extends SeleneseTestBase {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
try {
driver.get("https://www.blueshieldca.com/fap/app/search.html");
driver.findElement(By.id("location"))
.sendKeys("Locans, Fresno, CA");
driver.findElement(By.className("findNow")).click();
Thread.sleep(1000);
driver.findElement(By.className("continueBtn")).click();
Thread.sleep(15000);
driver.findElement(
By.xpath("//ul[#id='doctortypesmodule']/li[2]/input"))
.click();
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
This works!!
Your actual issue is with wait
#BeforeTest
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.blueshieldca.com/fap/app";
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
#Test
public void Test01() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 60);
driver.get(baseUrl + "/search.html");
driver.findElement(By.xpath("//input[#name='location']")).clear();
driver.findElement(By.xpath("//input[#name='location']")).sendKeys(
"Los Alamitos, Orange, CA");
driver.findElement(By.xpath("//input[#value='findNow']")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//input[#onclick='continueallPlans();']"))
.click();
wait.until(ExpectedConditions.elementToBeClickable(By
.xpath("//input[#onclick='javascript:results_OnProviderCompareClicked(this);']")));
List<WebElement> ele = driver
.findElements(By
.xpath("//input[#onclick='javascript:results_OnProviderCompareClicked(this);']"));
System.out.println(ele.size());
ele.get(0).click();
}
Prashanth Sams | seleniumworks.com