How to continue running my testcases in the same window using selenium C#? - selenium

Please help me with this.
My second method is dependent on first method and so on.
I am not using driver.quit() or driver.close()
[TestMethod]
public void CheckInAsDcs()
{
Thread.Sleep(2000);
Assert.AreEqual(driver.Title, "NeuTravel");
var selectDropDown = driver.FindElement(By.Id("viewSelect"));
var dcsOption = driver.FindElements(By.TagName("option"))[1];
//checking for dcs in dropdown
var checkForDcs = driver.FindElement(By.Id("viewSelect"));
dcsOption.Click();
Thread.Sleep(2000);
}
[TestMethod]
public void CreateNewRequest()
{
//calling CheckInAsDcs function
CheckInAsDcs();
//waiting for the web elements to load
Thread.Sleep(10000);
//finding CreateNewRequest button and clicking it
var selectCreateNewReq = driver.FindElements(By.TagName("input"));
selectCreateNewReq[0].Click();
}

Related

How to check all opened windows with title in chrome using selenium

In chrome 3 windows opened but without closing any window need to check last open window title
tried driver.getTitle();
but It returns first window title
Reason is that I want get page title and performing any activity on last window.
First you can switch the window and then validate page. You can try this approach:
public void switchwindow() throws InterruptedException {
currentHandle = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allHandles = driver.getWindowHandles();
for (String handle : allHandles) {
if (!handle.equals(currentHandle)) {
driver.switchTo().window(handle);
break;
} else {
driver.switchTo().window(currentHandle);
Thread.sleep(8000);
}
}
}
Switch to parent window:
public void switchToParentWindow() throws InterruptedException {
Thread.sleep(5000);
driver.switchTo().window(currentHandle);
}

Selenium: How to drag and drop in Chrome using C#

The below code works in Firefox but not in Chrome. From what I could find online it seems that Actions.DragAndDrop does not work with Chrome. I am trying to move SVG elements.
Is there an alternative?
var action = new Actions(driver);
action
.DragAndDropToOffset(middle, 100, 100)
.Build()
.Perform();
Selenium.Webdriver: v3.141.0
Selenium.Webdriver.ChromeDriver: v76.0.3809.68
Selenium.Firefox.Webdriver: v0.24.0
Chrome: Version 76.0.3809.100 (Official Build) (64-bit)
This is what I use in Chrome. Remember when using drag and drop you need a starting element to click, and a second element where you are going to drop it.
Call:
var ele1 = Driver.FindElement(By.Xpath("//button[#class='cz2__images__image-content cz2__images--draggable']"));
var ele2 = Driver.FindElement(By.Xpath("//button[#class='Destination']"));
DragAndDrop(ele1, ele2);
Method:
public static void DragAndDrop(IWebElement element1, IWebElement element2)
{
WaitForElementEnabled(element1);
WaitForElementEnabled(element2);
var builder = new Actions(Driver);
var dragAndDrop = builder.ClickAndHold(element1).MoveToElement(element2).Release(element1).Build();
dragAndDrop.Perform();
}
or....
public static void test ()
{
var test1 = _webDriver.FindElement(By.Id("myid"));
var test2 = _webDriver.FindElement(By.Id("myid2"));
Actions builder1 = new Actions(_webDriver);
IAction dragAndDrop1 = builder1.ClickAndHold(test1).MoveToElement(test2).Release(test1).Build();
dragAndDrop1.Perform();
}
public void DragAndDropItem(IWebElement from, IWebElement to)
{
Actions action = new Actions(_driver);
action.DragAndDrop(from, to).Build().Perform();
}

How to handle multiple jQuery popup with selenium webdriver

I am working on java with selenium webdriver 2.39, we have application where multiple 'processing' popup is display for 2-5 sec and closed automatically, that is depend on data. Now, the question is how to handle this popup, this popup are jQuery popup. My script can only work further once all this three popup gets open and process data and get closed automatically. However, I can not use wait time as this script is used for load testing using JMeter, hence the process time may take more or less than 5 sec., Is there any way we can know if the popup exist or not on screen? I have used below given sample code but it returns only parent window and it does not identify jQuery popup, using below given code I can get if popup exist or not, but only if it is not jQuery popup. Can anyone help me?
public void FocusOnWindow() throws Exception{
int i=0;
do {
handles=driver.getWindowHandles();//get all windows
iterator = handles.iterator();
if(iterator.hasNext()){
subWindowHandler = iterator.next();
if(subWindowHandler==null){
i=0;
}else if(subWindowHandler!=null){
if(subWindowHandler!=parentWindowHandler){
popup = true;
i=2;
}
}
}
}while(i<2);
if(popup){
do{
handles=driver.getWindowHandles();
iterator = handles.iterator();
Thread.sleep(500);
if(iterator.hasNext()){
subWindowHandler = iterator.next();
if(subWindowHandler!=parentWindowHandler){
if(subWindowHandler==null){
String source = driver.getPageSource();
if(source==null){
i=2;
}
}
}else {
i=0;
}
//System.out.println("No any other popup.");
}
}while (i<2);
}
}
First of all, I'll strongly suggest not to put hard wait at all.
If you are aware of any of the element which is unique and part of post processing pop up screen (i.e. resulted user screen) then make use of selenium waitForElement() API function which intelligently wait for element to appear and once appeared performs further actions.
Take a look at this link which explains the advantages of using it.
And with Java bindings for selenium in place, You can use something like this -
WebDriverWait wait = new WebDriverWait(driver, /*seconds=*/3);
elementOfPage = wait.until(presenceOfElementLocated(By.id("id_of_element")));
Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
return new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
};
}
public boolean runScript(){
JavascriptExecutor js = (JavascriptExecutor) driver;
return (Boolean) js.executeScript("return jQuery.active==0;");
}
public void FocusOnWindow() throws Exception{
int i=0;
do {
if(!runScript()){
System.out.println("Popup exists");
i++;
}else{
i=5000;
System.out.println("Popup does not exists");
}
}while(i<5000);
}

How to deal with ModalDialog using selenium webdriver?

I am unable to switch to Modal Dialog of given example
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm
I don't know how to get element on modal Dialog
Use
following methods to switch to modelframe
driver.switchTo().frame("ModelFrameTitle");
or
driver.switchTo().activeElement()
Hope this will work
What you are using is not a model dialog, it is a separate window.
Use this code:
private static Object firstHandle;
private static Object lastHandle;
public static void switchToWindowsPopup() {
Set<String> handles = DriverManager.getCurrent().getWindowHandles();
Iterator<String> itr = handles.iterator();
firstHandle = itr.next();
lastHandle = firstHandle;
while (itr.hasNext()) {
lastHandle = itr.next();
}
DriverManager.getCurrent().switchTo().window(lastHandle.toString());
}
public static void switchToMainWindow() {
DriverManager.getCurrent().switchTo().window(firstHandle.toString());
Try the below code. It is working in IE but not in FF22. If Modal dialog found is printed in Console, then Modal dialog is identified and switched.
public class ModalDialog {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new InternetExplorerDriver();
//WebDriver driver = new FirefoxDriver();
driver.get("http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm");
String parent = driver.getWindowHandle();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement push_to_create = wait.until(ExpectedConditions
.elementToBeClickable(By
.cssSelector("input[value='Push To Create']")));
push_to_create.click();
waitForWindow(driver);
switchToModalDialog(driver, parent);
}
public static void waitForWindow(WebDriver driver)
throws InterruptedException {
//wait until number of window handles become 2 or until 6 seconds are completed.
int timecount = 1;
do {
driver.getWindowHandles();
Thread.sleep(200);
timecount++;
if (timecount > 30) {
break;
}
} while (driver.getWindowHandles().size() != 2);
}
public static void switchToModalDialog(WebDriver driver, String parent) {
//Switch to Modal dialog
if (driver.getWindowHandles().size() == 2) {
for (String window : driver.getWindowHandles()) {
if (!window.equals(parent)) {
driver.switchTo().window(window);
System.out.println("Modal dialog found");
break;
}
}
}
}
}
Solution in R (RSelenium):
I had a popup dialog (which is dynamically generated) and hence undetectable in the original page source code
Here are methods which worked for me:
Method 1: Simulating Pressing keys for Tabs and switching to that modal dialog
My current key is focussed on a dropdown button behind the modal dialog box
remDr$sendKeysToActiveElement(list(key = "tab"))
Sys.sleep(5)
remDr$sendKeysToActiveElement(list(key = "enter"))
Sys.sleep(15)
Method 2: Bring focus to the frame(or iframe) if you can locate it
date_filter_frame <- remDr$findElement(using = "tag name", 'iframe')
date_filter_frame$highlightElement()
Sys.sleep(5)
remDr$switchToFrame(date_filter_frame)
Sys.sleep(2)
Now you can search for elements in the frame. Remember to put adequate Sys.sleep in between commands for elements to load properly (just in case)
date_filter_element <- remDr$findElement(using = "xpath", paste0("//*[contains(text(), 'Week to Date')]"))
date_filter_element$highlightElement()
Try this code, include your object names & variable to work.
Set<String> windowids = driver.getWindowHandles();
Iterator<String> iter= windowids.iterator();
for (int i = 1; i < sh.getRows(); i++)
{
while(iter.hasNext())
{
System.out.println("Main Window ID :"+iter.next());
}
driver.findElement(By.id("lgnLogin_UserName")).clear();
driver.findElement(By.id("lgnLogin_UserName")).sendKeys(sh.getCell(0,
i).getContents());
driver.findElement(By.id("lgnLogin_Password")).clear();
driver.findElement(By.id("lgnLogin_Password")).sendKeys(sh.getCell(1,
i).getContents());
driver.findElement(By.id("lgnLogin_LoginButton")).click();
Thread.sleep(5000L);
windowids = driver.getWindowHandles();
iter= windowids.iterator();
String main_windowID=iter.next();
String tabbed_windowID=iter.next();
System.out.println("Main Window ID :"+main_windowID);
//switch over to pop-up window
Thread.sleep(1000);
driver.switchTo().window(tabbed_windowID);
System.out.println("Pop-up window Title : "+driver.getTitle());
I have tried it, it works for you.
String mainWinHander = webDriver.getWindowHandle();
// code for clicking button to open new window is ommited
//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();
for(String handle : handles)
{
if(!mainWinHander.equals(handle))
{
// Here will block for ever. No exception and timeout!
WebDriver popup = webDriver.switchTo().window(handle);
// do something with popup
popup.close();
}
}
Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.
WebElement link = // element that will showModalDialog()
// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
"var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
link);
// wait for there to be two windows and choose the one that is
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
.until(new Function<WebDriver, Boolean>() {
#Override
public Boolean apply(final WebDriver driver) {
final String[] windowHandles =
driver.getWindowHandles().toArray(new String[0]);
if (windowHandles.length != 2) {
return false;
}
if (windowHandles[0].equals(parentWindowHandle)) {
driver.switchTo().window(windowHandles[1]);
} else {
driver.switchTo().window(windowHandles[0]);
}
return true;
}
});
Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model,
This will works once model appeared then control take a place into model and click the expected element.
have to import javascriptexector
like below,
Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);
P.S. 1 adding my 2 cents even though the question is too old
public void PressEnterKey()
{
var simulator = new InputSimulator();
simulator.Keyboard.KeyPress(VirtualKeyCode.RETURN);
}
you can create a method like the above and call it where it is required.
P.S. 2 - you can change the keyboard inputs as well (like up arrow, down arrow, page down etc)

Unable to control slider captcha jquery using Selenium Webdrive?

I want to record slider captcha given on our client site.
We have get this concept from other site named as http://www.fmylife.com/signup
This have slider captcha for registration
I have try to use selenium webdriver action builder
public class TestFmylife {
WebDriver driver;
Selenium selenium;
#BeforeMethod
public void startSelenium() {
driver = new FirefoxDriver();
selenium = new WebDriverBackedSelenium(driver, "http://www.fmylife.com/");
driver.manage().window().maximize();
}
#AfterMethod
public void stopSelenium() {
driver.close();
}
#Test
public void testFmylife() {
selenium.open("/");
selenium.click("link=Sign up");
selenium.waitForPageToLoad("30000");
selenium.type("name=login", "testfmylife");
selenium.type("name=pass", "123#fmylife");
selenium.type("name=passc", "123#fmylife");
selenium.type("name=mail", "testfmylife#gmail.com");
Point MyPoint= driver.findElement(By.xpath("//*[#id='bgSlider']")).getLocation();
WebElement someElement = driver.findElement(By.xpath("//*[#id='bgSlider']"));
System.out.println(MyPoint.x+"--------"+MyPoint.y);
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement).moveByOffset(MyPoint.x,(MyPoint.y + 100)).release().build();
dragAndDrop.perform();
selenium.click("css=div.form > div.ok > input[type=\"submit\"]");
}
}
But I can't move slider using this code
Help me to sort this out
I used the dragAndDropBy method of the Actions class (java.lang.Object
org.openqa.selenium.interactions.Actions) and moved the slider by 200 points horizontally . Please give the following code a try:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.fmylife.com/signup");
WebElement slider = driver.findElement(By.xpath(".//*[#id='Slider']"));
Actions builder = new Actions (driver);
builder.dragAndDropBy(slider, 200, 0).build().perform();
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();
more can be found at - http://code.google.com/p/selenium/wiki/AdvancedUserInteractions
You can use locator as follows -
String xto=Integer.toString(LocatorTo.getLocation().x);
String yto=Integer.toString(LocatorTo.getLocation().y);
Working code-
WebDriver driver = new InternetExplorerDriver();
driver.get("http://jqueryui.com/demos/slider/");
//Identify WebElement
WebElement slider = driver.findElement(By.xpath("//div[#id='slider']/a"));
//Using Action Class
Actions move = new Actions(driver);
Action action = move.dragAndDropBy(slider, 30, 0).build();
action.perform();
driver.quit();
Source - https://gist.github.com/2497551
If your slider is like mine
with a "slider handle" (an <a/> tag as the box with the value "5ft 5") within a "slider track" (a <div> tag as the long black bar) then the following code will in C# will work to move the slider handle a percentage along the slider track.
public void SetSliderPercentage(string sliderHandleXpath, string sliderTrackXpath, int percentage)
{
var sliderHandle = driver.FindElement(By.XPath(sliderHandleXpath));
var sliderTrack = driver.FindElement(By.XPath(sliderTrackXpath));
var width = int.Parse(sliderTrack.GetCssValue("width").Replace("px", ""));
var dx = (int)(percentage / 100.0 * width);
new Actions(driver)
.DragAndDropToOffset(sliderHandle, dx, 0)
.Build()
.Perform();
}