How can I avoid "no response from server URL" exception when using hub on Selenium remotewebdriver when object is not found? - selenium

This is the code I am getting error on line 1. Instead of returning true or false it throws an exception " No response from server for url: http://test:4444/wd/hub/session/1382359342795/element
Getting error on line1 :
Boolean tInputElement = driver.FindElement(By.Id("locator")).Enabled;
if (tInputElement.ToString() == "True")
{
IWebElement InputElement=driver.FindElement(By.Id("locator"));
InputElement.SendKeys(InputData);
}
Please suggest how can I avoid no response error and catch objectnotfoundexception. Please note I am running this code using Hub.
This is how I got this working :
int _TotalTimeToWait = 0;
int TotalTimeToWaitinSecs = 40;
while (_TotalTimeToWait < TotalTimeToWaitinSecs && driver.FindElements(by).Count == 0)
{
Thread.Sleep(1000);
_TotalTimeToWait++;
}
if (_TotalTimeToWait == 0) { driver.FindElement(by).Click(); Thread.Sleep(2000); }
else { throw new ElementNotVisibleException(); }
_TotalTimeToWait = 0;

As far as i know, there is no property like Enabled for WebElement, but it does have a IsEnabled() method, so try:
if (driver.FindElement(By.Id("locator")).isEnabled())
{
IWebElement InputElement=driver.FindElement(By.Id("locator"));
InputElement.SendKeys(InputData);
}
Or something like:
IWebElement InputElement=driver.FindElement(By.Id("locator"));
if (InputElement != null && InputElement.isEnabled())
{
InputElement.SendKeys(InputData);
}

Related

Get this warning with latest Chromedriver: Unable to evaluate script: disconnected: not connected to DevTools . How to resolve this?

I get this warning in eclipse : Unable to evaluate script: disconnected: not connected to DevTools when running cucumber selenium script.
image of the warning
I am using the latest Chrome driver version. Since this issue, the following code does not give the out put.
enter code here public boolean isMixedContentWarningsAppearing() {
String warning = null;
boolean result = true;
try {
LogEntries entry = driver.manage().logs().get(LogType.BROWSER);
List<org.openqa.selenium.logging.LogEntry> logs = entry.getAll();
for (org.openqa.selenium.logging.LogEntry e : logs) {
if (e.toString().contains("Accessing")) {
System.out.println("..... warnings...." + e);
warning = e.toString();
// Reporter.addStepLog(warning);
}
}
} catch (Exception e) {
}
if (warning == null) {
result = false;
Reporter.addStepLog("No MixedContent warnings");
} else {
result = true;
Reporter.addStepLog("The application contains Mixed Contents");
}
return result;
}
can anybody help me to run this code?

wait.until(ExpectedCondition) generating error

After upgrading to selenium Java 3.8.1 the wait.until(ExpectedCondition) has started giving error message.
For the following piece of code
WebElement framei = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='ctl00_ContentPlaceHolder1_dlgModal_IFrame']")));
driver.switchTo().frame(framei);
WebElement AcceptRadioButton=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='RblStatus']/tbody/tr[1]/td/label")));
AcceptRadioButton.click();
The following error is given:
Type The method until(Function<? super WebDriver,V>) in the type FluentWait<WebDriver> is not applicable for the arguments (ExpectedCondition<WebElement>)
I tried to resolve the following issue by removing the Selenium java version 3.8.1 of
Same problem as you but not so sure about Eugene S answer I search in sources of selenium-java 2.53.1 and 3.8.1 to see what was different between FluentWait class. Here are until fonctions of the different version:
2.53.1 :
public void until(final Predicate<T> isTrue) {
until(new Function<T, Boolean>() {
public Boolean apply(T input) {
return isTrue.apply(input);
}
public String toString() {
return isTrue.toString();
}
});
}
OR
public <V> V until(Function<? super T, V> isTrue) {
long end = clock.laterBy(timeout.in(MILLISECONDS));
Throwable lastException = null;
while (true) {
try {
V value = isTrue.apply(input);
if (value != null && Boolean.class.equals(value.getClass())) {
if (Boolean.TRUE.equals(value)) {
return value;
}
} else if (value != null) {
return value;
}
} catch (Throwable e) {
lastException = propagateIfNotIgnored(e);
}
// Check the timeout after evaluating the function to ensure conditions
// with a zero timeout can succeed.
if (!clock.isNowBefore(end)) {
String message = messageSupplier != null ?
messageSupplier.get() : null;
String toAppend = message == null ?
" waiting for " + isTrue.toString() : ": " + message;
String timeoutMessage = String.format("Timed out after %d seconds%s",
timeout.in(SECONDS), toAppend);
throw timeoutException(timeoutMessage, lastException);
}
try {
sleeper.sleep(interval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new WebDriverException(e);
}
}
}
AND IN 3.8.1:
public <V> V until(Function<? super T, V> isTrue) {
long end = clock.laterBy(timeout.in(MILLISECONDS));
Throwable lastException;
while (true) {
try {
V value = isTrue.apply(input);
if (value != null && (Boolean.class != value.getClass() || Boolean.TRUE.equals(value))) {
return value;
}
// Clear the last exception; if another retry or timeout exception would
// be caused by a false or null value, the last exception is not the
// cause of the timeout.
lastException = null;
} catch (Throwable e) {
lastException = propagateIfNotIgnored(e);
}
// Check the timeout after evaluating the function to ensure conditions
// with a zero timeout can succeed.
if (!clock.isNowBefore(end)) {
String message = messageSupplier != null ?
messageSupplier.get() : null;
String timeoutMessage = String.format(
"Expected condition failed: %s (tried for %d second(s) with %s interval)",
message == null ? "waiting for " + isTrue : message,
timeout.in(SECONDS), interval);
throw timeoutException(timeoutMessage, lastException);
}
try {
sleeper.sleep(interval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new WebDriverException(e);
}
}
}
I don't see any difference between the three functions arguments but the project I work on did not return me any error with 2.53.1 version but with 3.8.1 I have the same error than Akhil.
As it says in the error message:
FluentWait<WebDriver> is not applicable for the arguments (ExpectedCondition<WebElement>)
Starting from Selenium 3, until method declaration now looks like this:
public <V> V until(Function<? super T, V> isTrue)
where Function is:
public interface Function<T, R>
So it has been converted to use Java 8 functional interface. You will need to rewrite your expected conditions accordingly.
As per best practices we must try to switch to a <iframe> with proper WebDriverWait as follows :
new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[#id='ctl00_ContentPlaceHolder1_dlgModal_IFrame']")));

AsyncTask doInBackground() does not execute correctly on run, but works on debugger

#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
ArrayList<HashMap<String, String>> PLIST = new ArrayList<>();
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(jsonUrl);
ArrayList<String> URLList = new ArrayList<>();
if (jsonStr != null) {
placesList.clear();
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray placesJsonArray = jsonObj.getJSONArray("results");
String pToken = "";
// looping through All Places
for (int i = 0; i < placesJsonArray.length(); i++) {
JSONObject placesJSONObject = placesJsonArray.getJSONObject(i);
String id = placesJSONObject.getString("id");
String name = placesJSONObject.getString("name");
HashMap<String, String> places = new HashMap<>();
// adding each child node to HashMap key => value
places.put("id", id);
places.put("name", name);
PLIST.add(places);
}
//TODO: fix this...
if (SEARCH_RADIUS == 1500) {
Log.e(TAG, "did it get to 1500?");
try {
for (int k = 0; k < 2; k++) {
//error is no value for next_page_token... this
ERROR HERE
pToken = jsonObj.getString("next_page_token"); //if I place breakpoint here, debugger runs correctly, and returns more than 20 results if there is a next_page_token.
String newjsonUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
+ midpointLocation.getLatitude() + "," + midpointLocation.getLongitude()
+ "&radius=" + SEARCH_RADIUS + "&key=AIzaSyCiK0Gnape_SW-53Fnva09IjEGvn55pQ8I&pagetoken=" + pToken;
URLList.add(newjsonUrl);
jsonObj = new JSONObject(new HttpHandler().makeServiceCall(newjsonUrl)); //moved
Log.e(TAG, "page does this try catch");
}
}
catch (Exception e ) {
Log.e(TAG, "page token not found: " + e.toString());
}
for (String url : URLList){
Log.e(TAG, "url is : " + url);
}
I made an ArrayList of URLS after many attempts to debug this code, I planned on unpacking the ArrayList after all the urls with next_page_tokens were added, and then parsing through each of them later. When running the debugger with the breakpoint on pToken = getString("next_page_token") i get the first url from the Logger, and then the second url correctly. When I run as is, I get the first url, and then the following error: JSONException: No value for next_page_token
Things I've tried
Invalidating Caches and restarting
Clean Build
Run on different SDK versions
Made sure that the if statement is hitting (SEARCH_RADIUS == 1500)
Any help would be much appreciated, thanks!
Function is called in a listener function like this.
new GetPlaces(new AsyncResponse() {
#Override
public void processFinish(ArrayList<HashMap<String, String>> output) {
Log.e(TAG, "outputasync:" );
placesList = output;
}
}).execute();
My onPostExecute method.
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
delegate.processFinish(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
It turns out that the google places api takes a few milliseconds to validate the next_page_token after it is generated. As such, I have used the wait() function to pause before creating the newly generated url based on the next_page_token. This fixed my problem. Thanks for the help.

Selenium IDE generate code not using WebDriverWait.Until

When generating NUnit code from selenium ide, wait commands like clickAndWait generate an awkward pattern using a loop.
Wouldn't it be better to use a WebDriverWait.until?
Or am I getting something wrong?
UPDATE:
Sorry, wrote from memory, the code i was referring to is on the waitForElementcommand and not clickAndWait.
This is the code i'm referring to:
// waitForElementPresent | id=id |
for (int second = 0; ; second++)
{
if (second >= 60) Assert.Fail("timeout");
try
{
if (IsElementPresent(By.Id("id"))) break;
}
catch (Exception)
{ }
Thread.Sleep(1000);
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
Reading various guides and other answers, it seems to me that a better solution would be this one:
// waitForElementPresent | id=id |
if (!WaitForElementPresent(By.Id("id"))) { Assert.Fail(); }
private bool WaitForElementPresent(By by)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
try
{
wait.Until(drv => drv.FindElement(by));
return true;
}
catch (Exception)
{
return false;
}
}
Yes, using WebDriverWait is the better approach to wait for element exist, But instead of creating own custom ExpectedConditions you should use selenium provided ExpectedConditions.ElementExists function to wait until element exist as below :-
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
IWebElement el = wait.Until(ExpectedConditions.ElementExists(by));
Hope it helps..:)

checking for element present or not using Selenium WebDriver page factory?

Checking for elements with findElements using normal WebDriver method is easy like:
boolean exists = driver.findElements( By.id("...") ).size() != 0
Elements initialized by Page Factory are like:
#FindBy(name = "filter")
private WebElement filterText;
But how can we check in our page that this element is present on the page or not ??
The isDisplayed() method should do the job:
if (filterText.isDisplayed()) {
filterText.doStuff();
}
here's something i came up with:
public boolean isElementPresent(WebElement we)
{
try {
we.getTagName();
} catch (NoSuchElementException e) {
flag = 1;
}
if (flag == 1)
return true;
else
return false;
}
which is pretty basic but effective way to do it..