How to do a forced page refresh using selenium webdriver? - selenium

In my automation, at one point I have to refresh the page to get the updated page content. But during the refresh the webpage is asking for a confirmation to resend the data (basically an alert is displayed on the page).
Even though I switched the focus to the alert and accepted it, the page contents are not getting refreshed. If I manually do the same, page contents are getting refreshed.
Is there any alternative way to refresh the page using Selenium Webdriver apart from navigate().refresh() command?
Or is there any way I can click on the Retry button on the alert without accepting the alert??

In ruby try using this - #driver.switch_to.alert.accept
this will click on Resend
java code driver.switchTo().alert().accept();

Refreshing Page in Selenium Webdriver using Java:
public boolean refresh()
{
boolean executedActionStatus = false;
try{
((JavascriptExecutor)driver).executeScript("document.location.reload()");
Thread.sleep(2000);
executedActionStatus = true;
}
catch(Exception er)
{
er.printStackTrace();
getScreenShot(method_TableName, "ExpCaseShot");
log.error(er);
}
return executedActionStatus;
}

Related

Selenium Web Driver

We are working on IE Automation using Selenium Web driver in C#.Net.
We are getting an exception in handling model popup window. We supposed to do below the action.
When we click on Link button it will open a popup window then we need switch to popup window selecting check box options and click on Submit button.
When clicking on Link button we are able to open the popup window. But here we are facing an issue like the child popup window is not loading with data and getting HTTP 500 Internal server Error.
I don't understand sometimes it was working properly with the same code but not all the times I am getting above issue when I am trying to perform above actions on child window.
is this any IE settings issue or my code issue even i ignored protected mode settings in IE settings.
I am trying with below code :
js.ExecuteScript("arguments[0].click();", driver.FindElement(By.XPath("//*[#id='ByNewNotes']")));
(or)
string jsWindowString = "NewWindow('pop_Type.jsp?Type=External&IuserId=NUVJK50'," + sessionId + ",'400','500');return false";
((IJavaScriptExecutor)driver).ExecuteScript(jsWindowString);
Could you please help on this issue.
Thanks in Advance.
Instead of using ExpectedConditions.ElementEx‌​ists use ExpectedConditions.elementToBeClickable or presenceOfElementLocated
WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(""//*[‌​#id='ByNewNotes']")));
element.click();
Either Try to use FluentWait. Create a by function of your element which you want to wait and pass it in below method
WebElement waitsss(WebDriver driver, By elementIdentifier){
Wait<WebDriver> wait =
new FluentWait<WebDriver>(driver).withTimeout(60, TimeUnit.SECONDS) .pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
return wait.until(new Function<WebDriver, WebElement>()
{
public WebElement apply(WebDriver driver) {
return driver.findElement(elementIdentifier);
}});
}
Hope it will help you :)
Have you tried
Thread.Sleep(2000);
We had the same issues and solved it with this simple way.

Verify that authentication browser popup exists

I have a list of sites and some sites show an authentification window when the site is opened, I need to know what sites show this authentication popup, and which are not.
I'm trying to verify that authentication browser popup shows after page open. But when I use:
Alert alert = driver.switchTo().alert();
alert.accept();
I get an error:
no alert open(Session info: chrome=59.0.3071.115)(Driver info: chromedriver=2.30.477691(6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-83-generic x86_64) (WARNING: The server did not provide any stacktrace information)
Of course, an authentication window appears on the site. enter image description here
One more thing, I don't need authorize on this site, I just need to make sure, that the window appeared.
You can create/modify the method isAlertPresent as given below and try it. It may help you.
First confirm with below method if the alert present
public boolean isAlertPresent() {
try{
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
catch (NoAlertPresentException noAlert) {
return false;
}
catch (TimeoutException timeOutEx){
return false;
}
}
If above not work then JavascriptExecutor worked for you. Just take care that you should execute it before clicking the event which invoke alert.
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked
It's an authentication pop-up. You can handle it like below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));
OR
driver.get("http://UserName:Password#Example.com");
To Press ESC :-
Use action class
Actions action = new Actions(driver);
action.sendKeys(Keys.ESCAPE).build().perform();
Robot class code :-
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
Hope it will help you :)

Facing issues in Alertbox selenium 3.0

After clicking save button a pop will open and i write a code below to do accept but its not working.
`driver.findElement(By.id("save")).click();
Alert succ=driver.switchTo().alert();
System.out.println(succ.getText());
Thread.sleep(2000);
succ.accept();`
Need Help please.
The behavior of selenium varies according to browser, In some case the actions done in Firefox browser like form filling actions or clicking the button is faster then Chrome browser so your script well executed in chrome but throw error in Firefox so you need to add some pause to make them perform well.
So in your case after clicking the save button selenium executing the command too fast so skip to switch on alert and accept so add some wait using Thread.sleep(); to make pause
driver.findElement(By.id("save")).click();
Thread.sleep(2000);
Alert succ=driver.switchTo().alert();
System.out.println(succ.getText());
Thread.sleep(2000);
succ.accept();
Note : It is not recommended to use Thread.sleep(); instead use implicit or explicitwait conditions
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.alertIsPresent());
Try this:
driver.findElement(By.id("save")).click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(driver.switchTo().alert().getText());
driver.switchTo().alert().accept();

Why does Selenium "flicker" between finding and not finding a particular HTML element?

I'm using Specflow/Selenium to automate test of a web application I'm working on in the ASP.Net environment. Most of the 'button clicks' lead to complete page loads. I execute the following lines of code to execute when clicking such a button, but it's a flickering piece of code - sometimes it finds the element and other times it fails. Why is that?
public class CreateQuestionPOM : BasePOM
{
//Flickering find!
[FindsBy(How = How.XPath, Using = "//label[text()[contains(.,'True/False')]]")]
private IWebElement trueFalseOption;
[FindsBy(How = How.XPath, Using = "//a[#ct='Button' and #title='Next']")]
private IWebElement nextButton;
public CreateQuestionPOM(IWebDriver driver) : base(driver) { }
public void CreateTrueFalseQuestion()
{
trueFalseOption.Click();
nextButton.Click();
WebDriverWait wait = new WebDriverWait(GetDriver(), TimeSpan.FromSeconds(20));
wait.Until(driver1 => ((IJavaScriptExecutor)GetDriver()).ExecuteScript("return document.readyState").Equals("complete"));
}
}
The above method signature is similar to all button clicks that happen on the page. The above piece of code is called after a previous button is clicked. The method is very similar to the above - wait for document.readystate to be complete. But why does this flicker so often and what is the recommended solution?
There is no wait in your code, there is a wait.until(). When that code is executed, it is executed immediately and the until condition is checked. If the until condition is true, execution continues. Only if the until condition is false will there be a wait. If the code executes fast enough, the browser may not be transitioning to the next page before the until condition is checked. The until condition will pass because the current page (the page you clicked the element on) is already loaded. One thing you can try is to pick an element off the clicked page and wait for it to be stale. An element is stale when it is no longer in the DOM. When the next page is loaded, the elements on the previous page are stale. Try the code below and see if it helps.
public void CreateTrueFalseQuestion()
{
trueFalseOption.Click();
nextButton.Click();
WebDriverWait wait = new WebDriverWait(GetDriver(), TimeSpan.FromSeconds(20));
// when nextButton is stale you know the browser is transitioning...
wait.until(ExpectedConditions.stalenessOf(nextButton));
// ... then you wait for the new page to load
wait.Until(driver1 => ((IJavaScriptExecutor)GetDriver()).ExecuteScript("return document.readyState").Equals("complete"));
}

Selenium NoAlertPresentException

I'm trying to handle dialog (Ok Cancel type) with selenium WebDriver. So my aim is to click "Ok" button.
Scenario is:
Click button for invoking dialog
button.click();
Try to accept
webDriver.switchTo().alert().accept();
But I'm always getting NoAlertPresentException and seeing that dialog closes almost immediately.
It seems to me that Selenium automatically closes dialog and when I want to accept, there is nothing to accept.
I'm sorry for my bad English.
The usual cause of this issue is that Selenium is too quick and tries to accept an alert that has not yet been opened by the browser. This can be simply fixed by an explicit wait:
button.click();
WebDriverWait wait = new WebDriverWait(driver, 5);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
Step 1:
public boolean isAlertPresent(){
boolean foundAlert = false;
WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
try {
wait.until(ExpectedConditions.alertIsPresent());
foundAlert = true;
System.out.println("isAlertPresent : " +foundAlert);
} catch (TimeoutException eTO) {
foundAlert = false;
System.out.println("isAlertPresent : " +foundAlert);
}
return foundAlert;
}
Step 2:
public boolean tocheck_POP_Dialog()
{ Alert alert;
try
{
alert=driver.switchTo().alert();
}
catch(NoSuchElementException elementException)
{
return false;
}
alert.accept(); //Close Alert popup
return true;
}
Step 3 :
if(dummyPage.isAlertPresent())
{
dummyPage.tocheck_POP_Dialog();
}
public boolean isAlertPresent(){
try{
Alert a = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
if(a!=null){
System.out.println("Alert is present");
driver.switchTo().alert().accept();
return true;
}else{
throw new Throwable();
}
}
catch (Throwable e) {
System.err.println("Alert isn't present!!");
return false;
}
}
Use explicit wait to check the alert and then do the operation. This might help you. :)
Generally it happens because Selenium commands run too quick and it tries to close the alert before it is open. Hence, adding a delay after click event should resolve the issue. Also, if you are using Safari browser for your test, there is some issue with SafariDriver in handling alerts. SafariDriver cannot handle alerts should provide you more details.
Some additional info. for future readers of this thread:
If this exception persists even after the wait aspect is addressed, please check if the following sequence of steps is effective in the test script:
the underlying Html page's DOM is queried/parsed for some purpose (e.g. to look for Form errors)
(before the) driver.switch_to.alert is attempted
When an Alert is shown over an Html page, if the Alert is overlooked and the DOM underlying the Html page is queried first, the Webdriver appears to loose track of the Alert & causes the Exception.
This was observed with: geckodriver 0.21.0, Firefox 66.0b10 (64-bit) ; python 3.6.1 Selenium driver 3.14 (for Python).
Performing (2) before (1) was found to resolve the issue.