Selenium SendKeys to JqueryUi Popup - selenium

I have been having troubles with Selenium on and off for quite a while now. So, I thought I would create a nice simple example and hopefully a selenium expert can show me:
what I am doing wrong; or
what is wrong with the website that I am driving.
For this exercise, I have created a simple console application with a view to logging in to a library website. Obviously, username and password are not correct. But the fact is, the code which I present below cannot even type characters in a text box which is visible on the page:
static void Main(string[] args)
{
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService(#"E:\");
var chromeOptions = new ChromeOptions();
chromeDriverService.Port = 7788;
var driver = new ChromeDriver(chromeDriverService, chromeOptions);
var nav = driver.Navigate();
nav.GoToUrl("http://sapln.ent.sirsidynix.net.au/client/charlessturt/");
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementExists(By.CssSelector("#libInfoContainer > div.loginLink > a"))).Click();
wait.Until(ExpectedConditions.ElementExists(By.Id("j_username"))).SendKeys("gfhjdskaf");
wait.Until(ExpectedConditions.ElementExists(By.Id("j_password"))).SendKeys("gfhdsjffd");
driver.FindElementById("submit_0").Click();
Console.ReadKey();
}
By all means, try and populate that text box. I would love to hear how you achieve it.
I am using:
v.2.43.1 of Selenium with the latest version of Chrome
v.2.43 of ChromeDriver

your dialog is opening in an iframe. You'll need to switch to that iframe before you can interact with the login form elements.
I didn't test your code, but you can follow the example below, by removing my comments:
static void Main(string[] args)
{
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService(#"E:\");
var chromeOptions = new ChromeOptions();
chromeDriverService.Port = 7788;
var driver = new ChromeDriver(chromeDriverService, chromeOptions);
var nav = driver.Navigate();
nav.GoToUrl("http://sapln.ent.sirsidynix.net.au/client/charlessturt/");
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementExists(By.CssSelector("#libInfoContainer > div.loginLink > a"))).Click();
assuming your iframe is the first found you can use something like...:
driver.switchTo().frame(driver.findElements(By.tagName("iframe").get(0)));
Since your iframe doesn't have an id, we can't simply do:
driver.switchTo().frame("id of frame");
It would be super convenient if you could give your iframe an id.
Now lets continue with your code:
wait.Until(ExpectedConditions.ElementExists(By.Id("j_username"))).SendKeys("gfhjdskaf");
wait.Until(ExpectedConditions.ElementExists(By.Id("j_password"))).SendKeys("gfhdsjffd");
driver.FindElementById("submit_0").Click();
Once you're logged in, you need to switch back to the default content
driver.switchTo().defaultContent();
Console.ReadKey();
}
Simply inject that iframe switch before you attempt to interact with dialog, and inject the defaultContent() switch at the end before attempting to do anything else with initial page and you're good.
Good luck!

Related

How to Capture Full page screenshot of using selenium WebDriver

I have created a Selenium Full page screenshot test for Responsive tests using selenium.
But if I am going to run against the SharePoint Site then it's not taking a full-page screenshot but If I'll give any particular public site to capture the screenshots.
Here is the code snippet:
public class resTest {
#Test(groups = {"Test1"})
public void ResTest() throws InterruptedException, IOException {
System.setProperty("webdriver.gecko.driver", "C:\\browserdriver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(getUrl());
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
//Enter email ID
WebElement enterEmail = wait.until(ExpectedConditions.elementToBeClickable(By.name("loginfmt")));
enterEmail.sendKeys(getUsername());
WebElement clickNext = wait.until(ExpectedConditions.elementToBeClickable(By.className("win-button")));
clickNext.click();
//Enter Password
WebElement SubmitPass = wait.until(ExpectedConditions.elementToBeClickable(By.name("passwd")));
SubmitPass.sendKeys(getPassword());
//Click on Sign In button
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#value='Sign in']")));
element.click();
WebElement afterNext = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#value='No']")));
afterNext.click();
Thread.sleep(9000);
File src = ((FirefoxDriver)driver).getFullPageScreenshotAs(OutputType.FILE);
FileHandler.copy(src, new File(System.getProperty("user.dir")+"/Res2/screen.png"));
}
}
On a headless browser I use the following to get a screen of the full page
full_width = driver.execute_script('return document.body.parentNode.scrollWidth')
full_height = driver.execute_script('return document.body.parentNode.scrollHeight')
driver.set_window_size(full_width, full_height)
driver.save_screenshot(path)
The advantage of a headless browser window is that you can resize it to whatever size you want, even if it is larger than your screen resolution. For example, if your screen is 1920x1080 and you resize the headless browser window to 1000x5000 and take a screenshot, then the image will be 1000x5000 pixels.

clicking multiple links on a given webpage to open them in a new tab gives error

I'm trying to open each link on the given web page in a new tab But by clicking two links, it throws this error. Any suggestions would help. Thanks.
Here is my code:
public class FirstClass {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("https://www.google.com/");
Actions action = new Actions(driver);
List<WebElement> web = driver.findElements(By.tagName("a"));
for (int i = 1; i < web.size(); i++) {
System.out.println(web.get(i).getText());
action.moveToElement(web.get(i)).keyDown(Keys.CONTROL).click().build().perform();
}
}
}
Here is an error which I got -
Exception in thread "main" org.openqa.selenium.JavascriptException: javascript error: Failed to execute 'elementsFromPoint' on 'Document': The provided double value is non-finite.
The code fails as some of the links in the Google Webpage are not displayed and can only be seen when certain actions are performed. The first link which results in failure of the code is "Report inappropriate predictions" link which can be seen when one clicks on the search bar.
To handle these links, one needs to traverse through the DOM when things get tricky. So, I added a JavaScriptExecutor to the code which comes into picture when a given link is not displayed.
Please use the below-mentioned code to open every link in the Google HomePage:
System.setProperty("webdriver.chrome.driver", "chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("https://www.google.com/");
Actions action = new Actions(driver);
List<WebElement> web = driver.findElements(By.tagName("a"));
for (int i = 0; i < web.size(); i++) {
if(web.get(i).isDisplayed()){
action.moveToElement(web.get(i)).keyDown(Keys.CONTROL).click().build().perform();
}else{
String url = web.get(i).getAttribute("href");
((JavascriptExecutor)driver).executeScript("window.open('" + url + "', '_blank');");
}
}
Hope this helps.

Using Selenium web driver, not able to take Screenshot of web page with tool-tip text displayed on it

I am trying to take screen shot of the web page showing the tool tip text, but I can only see WebElement text being highlighted after mouse hover, but tool tip is not even shown up on the web page during script execution.
Here is the piece of code, that I am trying to execute. Need help to figure out what am I missing..
public static void main(String[] args) throws InterruptedException, IOException, AWTException
{
String URL = "https://www.rediff.com";
System.setProperty("webdriver.chrome.driver", "C:\\Users\\bhara\\eclipse-workspace\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(URL);
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
String WebElementXpath = "//*[#class='mailicon']";
String toolTipText ;
WebElement ToolTipElement = driver.findElement(By.xpath(WebElementXpath));
Actions act1 = new Actions(driver);
act1.moveToElement(ToolTipElement).build().perform();
Robot robot = new Robot();
Point point;
point = ToolTipElement.getLocation();
int x = point.getX();
int y = point.getY();
robot.mouseMove(x,y);
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("screenshot.png"));
System.out.println( ToolTipElement.getAttribute("title"));
}
I don't see any such issues in your code block as such. However if you observe the HTML DOM of the WebElement:
The text Lightning fast free email is the title attribute but not the tooltip as such. Hence through using Actions class to Mouse Hover over the element won't bring up the popup. However, I made some small changes and executed you code to get the same result as follows:
Code Block:
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
options.setExperimentalOption("useAutomationExtension", false);
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.rediff.com/");
new Actions(driver).moveToElement(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#class='mailicon']")))).build().perform();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(".\\Screenshots\\Rediffmail.png"));
System.out.println(driver.findElement(By.xpath("//a[#class='mailicon']")).getAttribute("title"));
driver.quit();
Console Output:
Lightning fast free email
Screenshot:

How can i make selenium wait till the next page is loaded with same URL and have same fields

I have this code show below:
driver.findElement(By.id("submit")).sendKeys(Keys.ENTER);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("search-trigger")).sendKeys(Keys.ENTER);
driver.findElement(By.id("search-trigger")).sendKeys("Shampoo");
driver.findElement(By.id("search-trigger")).sendKeys(Keys.ENTER);
I want to search for a product and search option is before and after login page but here i want to do it after login page
I have used
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
but it doesn't work and i cannot use
WebElement “”= driver.findElement(By.id(""));
as the search option is on both pages
and URL remains same after login also
Per my understanding, in short, you want to ensure user has logged in before searching for a product. However u will not be able to use WebElement “”= driver.findElement(By.id(""));
Did you try explicit wait for the presence of username/logout text...etc
WebElement element = wait.until(ExpectedConditions.elementIsVisible(By.id(>someid>)));
Below worked for me, tried searching Samsung after login in flipkart:
public static void f() throws InterruptedException
{
By signin = By.xpath(".//*[#id='container']/div/header/div[1]/div[1]/div/ul/li[9]/a");
Thread.sleep(2000);
By mobile = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[1]/input");
By password = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[2]/input");
By login = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[3]/button");
By myaccount = By.xpath(".//*[#id='container']/div/header/div[1]/div[1]/div/ul/li[8]/a");
By search = By.xpath(".//*[#id='container']/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[1]/div/input");
//geko driver for firefox
System.setProperty("webdriver.gecko.driver", "path of geckodriver.exe");
System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.flipkart.com/");
driver.findElement(signin).click();;
driver.findElement(mobile).sendKeys("xxxxxxxxx");
driver.findElement(password).sendKeys("xxxxxxxx");
driver.findElement(login).click();
WebDriverWait wait = new WebDriverWait (driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(myaccount));
driver.findElement(search).sendKeys("samsung");
}

KeyPress Enter for Selenium

We are doing automation testing and came around with a situation where i need to download the file from the browser .
In Download when the download button is hit we are coming to the system pop for the download where we need to perform the enter operation .
Can some one help us how to perform the enter or keyboard operation currently we are using robot API but it is not working on grid system ,
Here is my code for robot can it be enhanced and used or do we have any alternate way to do it
******** Code *************
public void downloadReportFromMyExport(WebDriver driver, String downloadSufixId) throws AWTException,
InterruptedException
{
String downloadPrefixId = ConfigProperty.getConfig("downloadPrefixId").trim();
String[] suffix;
suffix = StringUtil.split(downloadSufixId, "TR_EXP_");
String suffixPart = suffix[0];
String completeId = downloadPrefixId.concat(suffixPart);
By id = By.id(completeId);
WebElement element = driver.findElement(id);
element.click();
Robot pressKey = new Robot();
pressKey.keyPress(KeyEvent.VK_ENTER);
pressKey.keyRelease(KeyEvent.VK_ENTER);
threadSleep("5");
pressKey.keyPress(KeyEvent.VK_ALT);
pressKey.keyPress(KeyEvent.VK_F4);
pressKey.keyRelease(KeyEvent.VK_F4);
pressKey.keyRelease(KeyEvent.VK_ALT);
logger.info("Downlaod Complete");
}
In firefox browser,
Solution-1
You can change the browser settings so that it saves all downloads to that location without asking.
Refer below link to know to change that setting in firefox.
https://support.mozilla.org/en-US/kb/startup-home-page-download-settings
Solution-2
By using firefox profile setting you can achieve this.
FirefoxProfile profile=new FirefoxProfile();
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.download.dir","C:\\Users\\Downloads\\"); profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver=new FirefoxDriver(dc);
yeah i've encountered the same issue
better change the browser settings to save in a particular path
for handling different browsers like,
in FF,
i've used
in firefox by default the control will be on "OPEN" option so..
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
for IE (to save alt+s,to open alt+O) here im saving the file
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
for chrome
by default,when ever you click dowload button it will save without showing any popups
and i've succeeded hope it helps you
-Ajay