I am working on Selenium webDriver in which I am using the method driver.manage().deleteAllCookies();
But this method is deleting all cookies from the current domain except one. Strange!!
I am using Chrome right now.
Can anyone suggest what could be the possible cause and what we can do to delete all cookies for the current domain?
driver.manage().deleteAllCookies();
This will only delete cookies on current domain. It won't delete cookies of any other domain.
So if you need to delete cookies of those domain then you need to first browse to a page from that domain and then call the deleteAllCookies method again
I had to wait all ajax operations to finish then call deleteAllCookies(), then it worked.
public void ajaxWait(long seconds) {
try{
while(!waitForJSandJQueryToLoad()) {
try {
Thread.sleep(1000);
seconds -= 1;
if (seconds <= 0) {
return;
}
} catch (InterruptedException var4) {
var4.printStackTrace();
}
}
} catch(Exception e){
e.printStackTrace();
}
}
public boolean waitForJSandJQueryToLoad() {
WebDriverWait wait = new WebDriverWait(driver, 20);
// wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
try {
return ((Long)((JavascriptExecutor)driver).executeScript("return jQuery.active") == 0);
}
catch (Exception e) {
// no jQuery present
e.printStackTrace();
return true;
}
}
};
// wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState")
.toString().equals("complete");
}
};
return wait.until(jQueryLoad) && wait.until(jsLoad);
}
I had the same issue. I wanted to log out of the system. I thought that I had deleted all cookies by calling:
driver.manage().deleteAllCookies();
After the statement finished, however, the system navigated me to the home page.
The solution for me is to navigate to log in page then delete the cookies again:
driver.get(target_url);
driver.manage().deleteAllCookies();
Related
How can I create click method which can be click in the button until the attribute shows? Something like loop until but with timer (if it's not found attribute after 10 seconds, display an error). I have created something like that, but code give me NullPointerException when not found attribute:
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
WebElement button = driver.findElement(By.xpath("xpath"));
String attribute = button.getAttribute("disabled");
button.click();
if(attribute .equals("true"))
return true;
else
return false;
}
});
I got similar problem and my solution was to write a function that tries to click on the object and when it is not present it waits a second and tries once again. After 10 times of trying it returns null.
It works beautifully for me. Goes like this:
WebElement tryfind(WebDriver browser, By id)
{
WebElement ttwel=null;
for (int i=0;i<10;i++)
{
try
{
ttwel=browser.findElement(id);
break;
}
catch (NoSuchElementException ex)
{
sleep(1000);
}
}
return ttwel;
}
void sleep(int mills)
{
try
{
Thread.sleep(mills);
}
catch (InterruptedException ex)
{
}
}
You might add waiting for disabled attribute to this method, something like:
for (int i=0;i<10;i++)
{
try
{
ttwel=browser.findElement(id);
String attribute = button.getAttribute("disabled");
if (attribute==null) sleep(1000);
else break;
}
catch (NoSuchElementException ex)
{
sleep(1000);
}
}
Why don't you add a try catch block like this below to catch the NullPointerException and return false in that case
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
WebElement button = driver.findElement(By.xpath("xpath"));
try {
String attribute = button.getAttribute("disabled");
button.click();
if (attribute.equals("true")) {
return true;
}
} catch (NullPointerException e) {
return false;
}
return false;
}
});
I have this method implemented some time ago. I use it pretty extensively in my web automation.
The gist is to wait for one of several elements to be visible.
public void waitForSomeElementToBeVisible(int timeout, final By... locators) throws Exception, TimeoutException {
boolean found = false;
try {
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(driver, timeout);
ExpectedCondition<?>[] conditionsToEvaluate = new ExpectedCondition[locators.length];
for (int i = 0; i < locators.length; i++) {
conditionsToEvaluate[i] = ExpectedConditions.visibilityOfElementLocated(locators[i]);
}
found = wait.until(ExpectedConditions.or(conditionsToEvaluate));
} catch (TimeoutException e) {
throw e;
} catch (Exception e) {
throw e;
} finally {
driver.manage().timeouts().implicitlyWait(<default>, TimeUnit.SECONDS);
}
if (!found) throw new Exception("Nothing found");
}
Now I’m trying to use this method with a mobile browser. Specifically, iOS Safari via Appium. It works on iOS occasionally but usually fails and in the Appium log I see when executing the line:
found = wait.until(ExpectedConditions.or(conditionsToEvaluate));
(It does work consistently with Android+Appium).
[WD Proxy] Got response with status 404: {"value":{"error":"no such alert","message":"An attempt was made to operate on a modal dialog when one was not open","traceback":""},"sessionId":"03E95205-9E98-4DB4-BB61-0F125C2C5B3E"}
[debug] [W3C] Matched W3C error code 'no such alert' to NoSuchAlertError
There is, of course, no alert AND one of the elements does exist.
What’s going wrong here?
Is there a better way to wait for one of several elements to be visible?
Please try this java method :
public static boolean waitForElement(WebElement element) throws IOException {
log.info("Waiting for an element in the page...");
boolean isElementPresent = true;
try {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(element));
log.info("Element is visible");
return isElementPresent;
} catch (Exception e) {
log.info("waitForElement method failed! " + e.getMessage());
return !isElementPresent;
}
}
or this method:
public static WebElement fluentWait(final WebElement webElement, int timeinsec) {
log.info("waiting ..."+ timeinsec +" seconds");
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(timeinsec, TimeUnit.SECONDS).pollingEvery(timeinsec, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return webElement;
}
});
return element;
}
FYI: Both of these method are present under the below maven Dependency I created a while ago. It has a lot of re-usable method that you can use :
<dependency>
<groupId>com.github.mbn217</groupId>
<artifactId>MyUtilities</artifactId>
<version>1.0.2</version>
</dependency>
To use it you just need to call the class name and the method. No need to create an object from the class
example:
SeleniumUtils.waitForElement(pass your element here)
I am facing issues with Selenium when navigating from one page to another.
Below is the code. If I click on following element a jQuery image will open until the next page gets loaded. But it's not navigating to next page itself. The image keeps on rotating and window will close that. Why?
I am getting a NoSuchElementFoundException
Chrome Version : 58.0.3029.110
driver.findElement(By.name("continue")).click();
#Test
public void executeLoginApp() throws InterruptedException {
driver.navigate()
.to("url with login application");
WebElement userName = driver.findElement(By.id("uname"));
WebElement pwd = driver.findElement(By.id("passwd"));
userName.sendKeys("test");
pwd.sendKeys("test");
Thread.sleep(2000);
javaScriptExecutor.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Thread.sleep(2000);
//driver.findElement(By.xpath("//input[#name='continue']")).click();
//Thread.sleep(1000);
//driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
driver.findElement(By.name("continue")).click();
//signOn.click();
callYourInformation();
}
private void callYourInformation() {
/*try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String previousURL = driver.getCurrentUrl();
ExpectedCondition e = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return (d.getCurrentUrl() != previousURL);
}};
wait.until(e);}*/
// currentURL = driver.getCurrentUrl();
if (driver.getCurrentUrl().contains("yourinfo")) {
// testing yourinfo page
WebElement emailAddress = driver.findElement(By.id("emailAddress"));
emailAddress.clear();
emailAddress.sendKeys("selenium#wwwmail.com");
WebElement addressLine1 = driver.findElement(By.id("addressLine1"));
addressLine1.clear();
addressLine1.sendKeys("New york");
WebElement grossAnnualIncome = driver.findElement(By.id("grossAnnualIncome"));
grossAnnualIncome.sendKeys(String.valueOf(6000));
WebElement submit = driver.findElement(By.id("submitApplication"));
submit.click();
driver.findElement(By.id("Continue")).click();
}
else{
do other logic.
}
I tried all the ways but no luck. Commented lines are my tries but none of them redirects to that page.
I am writing tests for a web App using selenium webDriver and came across a scenario where when I try to delete a link the browser I get a popup saying:
Delete : "dummyname" Are you sure?
The browser page is asking you to confirm that you want to delete data, with 2 buttons: OK and cancel.
How do I click on those buttons?
For ok
driver.switchTo().alert().accept();
For cancel
driver.switchTo().alert().dismiss();
Hope it will help you :)
You should throw something like this in your BasePage.java and call acceptAlert() or dismissAlert(), but the magic lies in the code as Shubham Jain described above.
protected void acceptAlert() {
waitFor(new BooleanCondition() {
public Boolean apply(WebDriver webDriver) {
try {
webDriver.switchTo().alert().accept();
return true;
} catch (WebDriverException ex) {
return false;
}
}
public String describeFailure() {
return COULD_NOT_LOCATE_OR_ACCEPT_ALERT_BOX;
}
});
}
protected void dismissAlert() {
waitFor(new BooleanCondition() {
public Boolean apply(WebDriver webDriver) {
try {
webDriver.switchTo().alert().dismiss();
return true;
} catch (WebDriverException ex) {
return false;
}
}
public String describeFailure() {
return COULD_NOT_LOCATE_OR_ACCEPT_ALERT_BOX;
}
});
}
Please see my below code:
My if part of code is running successfully but my else part is not working.
The code gets skipped and is showing failure.
if (driver.findElement(By.id("error_explanation")).isDisplayed() == true) {
driver.findElement(By.id("user_email")).clear();
driver.findElement(By.id("user_email")).sendKeys("soumya50#toobler.com");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.id("user_password")).sendKeys("password");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.id("user_current_password")).sendKeys("password");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.name("commit")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.linkText("LOGOUT")).click();
} else
{
driver.findElement(By.linkText("REQUEST A PERMIT")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
Getting error as below:-
org.openqa.selenium.NoSuchElementException: Unable to locate element:
{"method":"id","selector":"error_explanation"}
In Selenium you should not use driver.findElement to check if an element exists or not.
Use driver.findElements instead. It returns a list of WebElement.
You can then check if the list is empty or not.
Please view this for more information
Use below code :-
1st way:-
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.get("URL");
By element=By.id("error_explanation"));
Boolean isPresent =isElementPresent(element);
System.out.println(isPresent);
if(isPresent==true)
{
System.out.println("yes");
}
else
{
System.out.println("No");
}
}
public boolean isElementPresent(By locatorKey) {
try {
driver.findElement(locatorKey);
return true;
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}
2nd way:-
By element=By.id("error_explanation"));
Boolean isPresent = driver.findElements(element).size() > 0;
System.out.println(isPresent);
if(isPresent==true)
{
System.out.println("yes");
}
else
{
System.out.println("No");
}
Create a new function as below,
public boolean findElementById(String id)
{
try {
webDriver.findElement(By.id(id));
} catch (NoSuchElementException e) {
return false;
}
return true;
}
check if condition as below in your code:
if (findElementById("error_explanation")) {
.....
}else {
.....
}
You are getting the error because when the element is not visible... it is apparently not on the page at all. You first need to check to see if the element exists, then see if it's visible.
The proper way to check if an element exists according to the Selenium docs is to use .findElements() and check for an empty List. I combined the .isEmpty() check with the .isDisplayed() check in your existing if. This should work now.
List<WebElement> errorExplanation = driver.findElements(By.id("error_explanation"));
if (!errorExplanation.isEmpty() && errorExplanation.get(0).isDisplayed())
{
driver.findElement(By.id("user_email")).clear();
driver.findElement(By.id("user_email")).sendKeys("soumya50#toobler.com");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.id("user_password")).sendKeys("password");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.id("user_current_password")).sendKeys("password");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.name("commit")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.linkText("LOGOUT")).click();
}
else
{
driver.findElement(By.linkText("REQUEST A PERMIT")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}