I'm currently using HtmlUnitDriver, and while I am able to set the username, I keep getting an error that Selenium could not find the password field. I am using JavascriptExecutor to set these values inside the PayPal sandbox form, but I'm still unable to get past the password step.
HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME)
JavascriptExecutor executor = (JavascriptExecutor)driver
driver.setJavascriptEnabled(true)
driver.get(url)
log.debug "setting username"
Thread.sleep(5000)
if(driver.findElement(By.xpath("//*[#id='email']")).displayed){
executor.executeScript("document.getElementById('email').value = 'email';")
log.debug "Username was set"
} else {
log.debug "We never set the username!"
}
if(driver.findElement(By.xpath("//*[#id='password']")).displayed){
executor.executeScript("document.getElementById('password').value='password';")
} else {
log.debug "We never set the password."
}
I understand that I am setting sleeps in there, and that's bad practice for Selenium testing, but I'm pretty much at my wits end here. The url in that case is the link to express checkout, which is something like this: https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=#################
Any help would be greatly appreciated!
As I mentioned earlier, there are multiple issues here:
When I load the initial page, I see this UI:
As you see, Password button is really invisible. So unless we click the Next button, there's no chance that this script will work.
So the following has to be added in order to achieve any kind of progress:
driver.findElement(By.id("btnNext")).submit()
However unfortunately I cannot get this button to be clicked correctly with HtmlUnitDriver. It seems button is clicked, but nothing happens, so Password field remains hidden. However as soon as I switch to ChromeDriver, this is not an issue anymore, and the same code works. So I guess you've hit one of the HtmlUnitDriver limitations, and need to use Chrome or Gecko driver.
Finally a few adjustments to the code will make it more reliable and faster. Here's the final version that works for "real" browsers (Chrome or Gecko):
WebDriver driver = new ChromeDriver()
WebDriverWait wait = new WebDriverWait(driver, 10)
driver.get(url)
// The following line waits for email field to appear. It's more economical and reliable than Thread.sleep
WebElement email = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")))
log.debug "setting username"
email.sendKeys("email#gmail.com")
log.debug "Username was set " + email.getAttribute("value")
driver.findElement(By.id("btnNext")).submit()
// Here again using the same method to verify when password becomes visible
WebElement password = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("password")))
log.debug "setting password"
password.sendKeys("password")
log.debug "Password was set " + password.getAttribute("value")
(note: I wrote this code in Java, so I hope I translated all correctly, but if I didn't feel free to fix it)
The result of this script looks like this in Chrome:
With HtmlUnitDriver, script will show an error:
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.id: email (tried for 10 second(s) with 500 MILLISECONDS interval)
Related
Does anybody know how to find this type of element by Selenium? (to validate its presence or text)?
I tried to catch it as alert (swithToAlert()) but it doesn't work. Any ideas? It is also can not be inspected as element and I can't find it in Elements. Thank you in advance.
This uses HTML5 form validation. This is created by the browser, and does not exist in the DOM. Therefore Selenium cannot see this.
You can access this using JavaScript. Here is a brief code sample:
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
WebElement field = driver.findElement(By.tagName("input")); // your input box
if (!(Boolean) jsExecutor.executeScript("return arguments[0].validity.valid;", field)) {
return (String) jsExecutor.executeScript("return arguments[0].validationMessage;", field);
}
The entire API is documented.
element.validity.valid
Returns true if the element's value has no validity problems; false otherwise.
So this popup is displayed if this returns false, but only after clicking Submit on the form.
I'm automating an application using Selenium so what is happening is when the script runs and it hits the login button an error comes up in the top right which stops further execution. What I want is need a way by which i can capture this "error message" so that I would know the cause of the halt of the application execution.I'm attaching the image of error and also the code that I have tried but it didnt work.
#FindBy(xpath="//*[#id='toast-container']/div/div]")
static WebElement errorMessage;
WebDriverWait wait = new WebDriverWait(CommonBrowserSetup.driver, 15);
wait.until(ExpectedConditions.visibilityOf(errorMessage));
String mess=errorMessage.getText();
System.out.println(mess);
If you want to capture Unknown error occured
Just try the following code and let me know if it works for you.
After the login button is clicked add the following:
WebElement Error = driver.findElement(By.xpath("//div[contains(text(),'Unknown error occured')]"));
if(Error.isDisplayed()){
String Errormessage = Error.getText();
System.out.println(Errormessage);
}
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
I'm trying to automate the webpage "http://www.quikr.com",when I open this you will get a pop up window first saying "Please Choose Your Location" then after closing it , I can see the main page of quikr.
I tried closing that Popup page by automation ,but not able to do
Tried using xpath
driver.findElement(By.xpath("//*[#id='csclose']/strong")).click();
Tried using className
driver.findElement(By.className("cs-close cs-close-v2")).click();
Tried using id
driver.findElement(By.id("csclose")).click();
Please help me with this
to close multiple popups in webdriver and switch to parent window
String parent = driver.getWindowHandle();
Set<String> pops=driver.getWindowHandles();
{
Iterator<String> it =pops.iterator();
while (it.hasNext()) {
String popupHandle=it.next().toString();
if(!popupHandle.contains(parent))
{
driver.switchTo().window(popupHandle);
System.out.println("Popu Up Title: "+ driver.switchTo().window(popupHandle).getTitle());
driver.close();
The Following Code Works for Me to Handle Pop Up/ Alerts in Selenium Webdriver
Just Copy Paste this Code After the Event which is triggering the Pop up/Alert i.e after clicking on save.
if(driver.switchTo().alert() != null)
{
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
alert.dismiss(); // alert.accept();
}
in your case you try to run this code at starting of the code bcz it will directly close the pop up
Since this is a JavaScript modal, when the page finishes loading the JavaScript code could still be running. The solution is to wait until the button to close the modal be displayed, close it and then follow with your test. Like this:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("csclose")));
driver.FindElement(By.Id("csclose")).Click();
Tested myself and works fine.
Hope it helps.
i have tried it in ruby and this one works
see if this can help you in any way :)
require 'selenium-webdriver'
require 'test/unit'
require 'rubygems'
class Tclogin < Test::Unit::TestCase #------------ define a class----------------
def setup
##driver = Selenium::WebDriver.for :firefox
##driver.navigate.to "http://www.quikr.com" #---- call url----
##wait = Selenium::WebDriver::Wait.new(:timeout => 60) # seconds #----define wait------
end
def test_login
##driver.find_element(:css, "strong").click
end
end
you can also use follwing xpath
##driver.find_element(:xpath, "//a[#id='csclose']/strong").click
public void closePopup() throws Exception {
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.quikr.com/");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("csclose"))).click();
System.out.println("Successfully closed the start Popup");
}
Try driver.findElement(By.Id("csclose")).click(); I hope that will help
Simple pressing Alt + F4 buttons worked for me, e.g.:
driver.findElement(By.cssSelector("html body div div img")).sendKeys(Keys.chord(Keys.ALT, Keys.F4));
In my automation, at one point I have to refresh the page to get the updated page content. But during the refresh the webpage is asking for a confirmation to resend the data (basically an alert is displayed on the page).
Even though I switched the focus to the alert and accepted it, the page contents are not getting refreshed. If I manually do the same, page contents are getting refreshed.
Is there any alternative way to refresh the page using Selenium Webdriver apart from navigate().refresh() command?
Or is there any way I can click on the Retry button on the alert without accepting the alert??
In ruby try using this - #driver.switch_to.alert.accept
this will click on Resend
java code driver.switchTo().alert().accept();
Refreshing Page in Selenium Webdriver using Java:
public boolean refresh()
{
boolean executedActionStatus = false;
try{
((JavascriptExecutor)driver).executeScript("document.location.reload()");
Thread.sleep(2000);
executedActionStatus = true;
}
catch(Exception er)
{
er.printStackTrace();
getScreenShot(method_TableName, "ExpCaseShot");
log.error(er);
}
return executedActionStatus;
}