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

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.

Related

How do I click on an element that appears sometimes 1 or sometimes 2 at different intervals

I have done this
List<WebElement> element= driver.findElements(By.xpath(""));
for(int i=0;element.size();i++)
{
driver.findElements(By.xpath("")).isDisplayed();
driver.findElements(By.xpath("")).click();
}
I am new to java and selenium , so I thought of doing this. Is this logic correct or am I wrong? If wrong(most probably) , can you please rectify and explain alongside , wud be very helpful.
I get element not interactable error on this.
In case you are looking for method to wait for one of two elements to appear and then to click on the appeared element you can use this method:
public String waitForOneOfTwoElements(String xpath1, String xpath2){
wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.or(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath1)),
ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath2))));
if(waitForElementToBeVisible(xpath1)){
return xpath1;
}else if(waitForElementToBeVisible(xpath2)){
return xpath2;
}
}catch (Throwable t){
return null;
}
}
Where waitForElementToBeVisible is:
public boolean waitForElementToBeVisible(String xpath) {
wait = new WebDriverWait(driver, 30);
try {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return true;
}catch (Throwable t) {
return false;
}
}
Now, when you get the appeared element you can simply click it with:
String appearedElementXpath = waitForOneOfTwoElements(xpath1,xpath2);
driver.findElement(By.xpath(appearedElementXpath)).click();

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

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;
}

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.......

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;
}
}