How Selenium getPageSource() work when we use switchTowindow is used? - selenium

What driver.getPageSource() method return if I switch the driver to some other window i have checked it is returning me the page source of the first page i.e. the first webpage I have launched how to get page source of current switched window..without relaunching the page....??
I have written the code like this I am successfully switching to the new window..but unable to get page source of current window...
public boolean switchToWindow(String title)
{
Set<String> availableWindows = webDr.getWindowHandles();
if (availableWindows.size() > 1)
{
try
{
for (String windowId : availableWindows)
{
if(webDr.switchTo().window(windowId).getTitle().equals(title))
{
return true;
}
}
} catch (Exception e) {
logger.handleError("No child window is available to switch ", e);
}
}
return false;
}

driver.getPageSource() should return the current active window source. From your code you can call driver.getPageSource() after switching to window.
public boolean switchToWindow(String title)
{
Set<String> availableWindows = webDr.getWindowHandles();
if (availableWindows.size() > 1)
{
try
{
for (String windowId : availableWindows)
{
if(webDr.switchTo().window(windowId).getTitle().equals(title))
{
System.out.println(driver.getPageSource());
return true;
}
}
} catch (Exception e) {
logger.handleError("No child window is available to switch ", e);
}
}
return false;
}

Related

(React Native) Huawei Location Kit - is there any way to know if network location services setting switch off?

to make our apps working indoor to fetch location we need Network Location Services switch to be on
And we're using this function to detect any setting that still off
We noticed the response which is LocationSettingsStates, when the switch on or off is always true
Am I using wrong function to detect it??
The class and methods mentioned in the original post are the right ones to be used for checking network location service availability.
Please refer to a partial code extracted from Huawei sample code obtained from Github
public void checkSettings(View view) {
new Thread() {
#Override
public void run() {
try {
CheckSettingsRequest checkSettingsRequest = new CheckSettingsRequest();
LocationRequest locationRequest = new LocationRequest();
checkSettingsRequest.setLocationRequest(locationRequest);
checkSettingsRequest.setAlwaysShow(false);
checkSettingsRequest.setNeedBle(false);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(checkSettingsRequest.getLocationRequest())
.setAlwaysShow(checkSettingsRequest.isAlwaysShow())
.setNeedBle(checkSettingsRequest.isNeedBle());
settingsClient.checkLocationSettings(builder.build())
.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(Task<LocationSettingsResponse> task) {
if (task != null && task.isSuccessful()) {
LocationSettingsResponse response = task.getResult();
if (response == null) {
return;
}
LocationSettingsStates locationSettingsStates =
response.getLocationSettingsStates();
stringBuilder.append(",\nisLocationPresent=")
.append(locationSettingsStates.isLocationPresent());
stringBuilder.append(",\nisLocationUsable=")
.append(locationSettingsStates.isLocationUsable());
stringBuilder.append(",\nisNetworkLocationUsable=")
.append(locationSettingsStates.isNetworkLocationUsable());
stringBuilder.append(",\nisNetworkLocationPresent=")
.append(locationSettingsStates.isNetworkLocationPresent());
stringBuilder.append(",\nisHMSLocationUsable=")
.append(locationSettingsStates.isHMSLocationUsable());
stringBuilder.append(",\nisHMSLocationPresent=")
.append(locationSettingsStates.isHMSLocationPresent());
LocationLog.i(TAG, "checkLocationSetting onComplete:" + stringBuilder.toString());
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception e) {
LocationLog.i(TAG, "checkLocationSetting onFailure:" + e.getMessage());
int statusCode = 0;
if (e instanceof ApiException) {
statusCode = ((ApiException) e).getStatusCode();
}
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
android.util.Log.i(TAG,
"Location settings are not satisfied. Attempting to upgrade "
+ "location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
if (e instanceof ResolvableApiException) {
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(CheckSettingActivity.this, 0);
}
} catch (IntentSender.SendIntentException sie) {
android.util.Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
default:
break;
}
}
});
} catch (Exception e) {
LocationLog.i(TAG, "checkLocationSetting exception:" + e.getMessage());
}
}
}.start();
}
The execution results when “network location service” is turned on and off are shown below. It shows the state with true and false respectively.
In some phone, LocationSettings interface may not be able to get the exact state.
You can set the Priority to be PRIORITY_BALANCED_POWER_ACCURACY and use requestLocationUpdatesWithCallback interface to get location update.
If the network location is not enabled, you will get the error code NETWORK_LOCATION_SERVICES_DISABLED 10105.
Then it means the switch is not enabled.

Selenium Testing : If element is not present then exception is not handled by Exception of type NoSuchElementException in Selenium

If any element doesnot exists in Selenium Testing, then I am unable to handle it. I have tried this code.
public static bool IsElementPresent(IWebDriver driver, By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
It shows timeout exception takes too much time more than 1 min and finally handled by main Exception class, but my automation testing stops, And I dont want to stop my testing.
I have tried this code snippet also.
public bool IsElementPresent(IWebDriver driver, By by, TimeSpan? timeSpan)
{
bool isElementPresent = false;
try
{
if (timeSpan == null)
{
timeSpan = TimeSpan.FromMilliseconds(2000);
}
var driverWait = new WebDriverWait(driver, (TimeSpan)timeSpan);
driverWait.IgnoreExceptionTypes(typeof(WebDriverTimeoutException));
isElementPresent=driverWait.Until(x => x.FindElements(by).Any());
return isElementPresent;
}
catch (NoSuchElementException nex)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
What should I do so that in small span of time it returns true or false.
Another option would be something like
return driver.FindElements(by).length > 0;
I generally use the Displayed property. I use the page object model with pre-determined IWebElements in the example below:
public bool IsPageObjectPresent(IWebElement PageObject)
{
try
{
if (PageObject.Displayed)
{
Console.WriteLine("Element is displayed");
return true;
}
else
{
Console.WriteLine("Element present but not visible");
return true;
}
}
catch (NoSuchElementException)
{
Console.WriteLine("Element not present");
return false;
}
catch (StaleElementReferenceException)
{
Console.WriteLine("Stale element present");
return false;
}
}
try{
// Add your complete portion of code here //
System.out.println("Portion of code executed Successfully");
}
catch(Exception name)
{
System.out.println("Portion of code failed");
}
Please try and let me know.......

Selecting a value from drop down other than Select Using Chrome driver

how to select a value from drop down which comes when we click in the text box but does not comes with select syntax Using Chrome
public boolean selectDropdown(WebElement element, String itemName) {
try {
if (select != null) {
List<WebElement> options = select.findElements(/*use a proper selector*/);
for (WebElement option : options) {
String sListBoxOption = option.getText();
if (sSelectItem.equalsIgnoreCase(sListBoxOption)){
option.click();
return true;
}
}
}
return false;
} catch (Exception e) {
return false;
}
}
You can send the web Element and the Item in the drop-down which you have to select as parameters for this method.

I am not able to switch to IFrame using Internet Explorer

I have developed a s keyword driven framework. It has a action keyword to switch the frame.
It works fine with Mozilla. But when it comes to IE it is not switching. It logs error.
IE driver -IEDriverServer_x64_2.44.0
IE version -9
Selenium version -selenium-java-2.44.0
Thanks in advance.
public static void switchFrame(String object,String data)throws Exception{
try{
driver.switchTo().frame("Ifrm");
Log.info("Switched the frame");
}
catch(Exception e){
Log.error("Not able to switch the frame--- " + e.getMessage());
DriverScript.bResult = false;
}
}
Here exception occurs.
I assume, the value you specified in frame is id/name/etc. You have to access the frame by calling the driver with specified value. Code would be
driver.switchTo().frame(driver.findElement(By.id("Ifrm")));
Selenium won't let me switch to the iframe by ID on Internet Explorer, but it does allow me to switch by index. If you have some sort of property that you can check that it is only available on the iframe you can do the following
new WebDriverWait(driver, 5).until(
new Predicate<WebDriver>() {
#Override
public boolean apply(WebDriver input) {
try {
int i = 1;
while (true) {
driver.switchTo().defaultContent();
driver.switchTo().frame(i);
String aClass =
driver.findElement(By.xpath("/html/body"))
.getAttribute("class");
if (aClass.contains("modal")) {
return true;
}
++i;
}
} catch (NoSuchFrameException e) {
return false;
}
}
}
);
In my case I was looking for a body class of modal

How to check if a new window is loaded successfully?

I have to access all the anchors on a specific div. Then, I have to assert if
the links are opened in a new window and
also make sure that the link is not broken.
How can this be done?
use findbyelements to collect list of links. Put them into a loop and select a link. then use "getWindowHandle" to switch to new window where an assertion can be implemented that "Page Doesn;t exist" or some other error message not displayed. This will ensure whether a link is broken
I used the following methods to verify if the links are opening a new window and are not broken. Code comments explains the code.
public boolean xAnchors()
{
String parentHandle = driver.getWindowHandle(); // get the current window handle
// System.out.println(parentHandle);
boolean isValidated = true;
try{
List<WebElement> anchors = wait.until(ExpectedConditions.visibilityOfAllElements(driver.findElements(By.xpath("//div[#class='container-with-shadow']//a")))); // This is an array of anchor elements
try
{
for (WebElement anchor : anchors){ //Iterating with the anchor elements
String anchorURL = anchor.getAttribute("href");
anchor.click();
String newWindow ="";
for (String winHandle : driver.getWindowHandles()) {
// System.out.println(winHandle);
driver.switchTo().window(winHandle); // switch focus to the new window
newWindow = winHandle; //Saving the new window handle
}
//code to do something on new window
if(newWindow == parentHandle) //Checking if new window pop is actually displayed to the user.
{
isValidated = false;
break;
}
else
{
boolean linkWorking = verifyLinkActive(anchorURL); //Verifying if the link is Broken or not
if(linkWorking)
{
System.out.println("The anchor opens a new window and the link is not broken");
isValidated = true;
}
else
{
System.out.println("The anchor either does not open a new window or the link is broken");
isValidated = false;
}
}
driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window
}
}
catch(Exception e)
{
isValidated = false;
}
}
catch(Exception e)
{
System.out.println("No Anchors founds on this page.");
isValidated = true;
}
System.out.println(isValidated);
return isValidated;
}
public boolean verifyLinkActive(String linkUrl){
try {
URL url = new URL(linkUrl);
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.setRequestMethod("GET");
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND){
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage()
+ " - "+ HttpURLConnection.HTTP_NOT_FOUND);
return false;
}
else
{
return true;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}