Using JAVA and SELENIUM LIBRARY:
I have a web automator that until now has worked flawlessly, using FirefoxDriver.
My code follows:
System.out.println("Creating new web driver");
WebDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);
System.out.println("Parsing CARD OFFICE PAGE\nAccessing webpage");
driver.get(myWebsite);
System.out.println("Setting login credentials");
WebElement id = driver.findElement(By.id("quickloginphrase"));
WebElement pw = driver.findElement(By.id("quickpassword"));
id.sendKeys(username);
pw.sendKeys(password);
System.out.println("Submitting credentials");
System.out.println(driver.getCurrentUrl());
pw.sendKeys(Keys.ENTER);
System.out.println("Credentials submitted");
Before I started using HTMLUnitDriver, the program managed to login to the webpage, but now I get redirected to a "login failed" page. I think the pw or username are being entered improperly. Is there some subtle difference between FirefoxDriver and HTMLUnitDriver that I'm not aware of?
well, possibly you come across with the following issues here:
1)
pw.sendKeys(Keys.ENTER);
enter button handler is not handled properly
2)
id.sendKeys(username);
pw.sendKeys(password);
you are sending improper login-pass
possible solution: try to press login button instean of pressing 'enter' key using
driver.findElement(By.xpath(//....blablabla)).click();
so I provide you some code which I use to login properly and validation of successful login:
public void doAdminLogin() throws IOException {
String curTitle=driver.getTitle();
locatorFindingHandling("login.logininput", "login.admin.login");
locatorFindingHandling("login.passinput", "login.admin.pass");
locatorFindingHandling("login.loginbutton");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String newTitle=driver.getTitle();
Assert.assertFalse(curTitle.equals(newTitle));
}
public void locatorFindingHandling(String key, String key1) throws IOException {
driver.findElement(By.xpath(propertyKeysLoader(key))).sendKeys(propertyKeysLoader(key1));
}
So as I've mentioned above try to investigate workaround. hope this works for you)
Related
I have two feature files in Cucumber that are linked to corresponding step files. The problem is that when one of the step file finishes execution then it closes all the browser windows (because of driver.quit()) whereby killing the execution of other step file which hasn't done processing yet.
Here each step file opens a new browser window, executes the tests within it and then closes and quits the browser. Currently I have just two step files but in the future there are going to be many more.
Is there anything in Cucumber that would always get executed after all the steps are executed?
How do I solve this problem?
HelpStep.java
#Ignore
public class HelpStep {
private WebDriver driver;
#Before
public void setup() {
System.out.println("Into the setup method of HelpStep...");
this.driver = BrowserConfig.getIEWebDriver();
}
#Given("^The user is on the Help page$")
public void onPage() {
System.out.println("The user is on the Help page");
}
#When("^The user clicks on the links within the Help page$")
public void clickLinks() {
System.out.println("The user clicks on the links within the Help page");
}
#Then("^The user is navigated to that section$")
public void validate() {
System.out.println("The user is navigated to that section");
}
#After
public void cleanUp() {
System.out.println("Into the cleanUp method of HelpStep...");
//FOLLOWING METHOD CALL KILLS ALL THE OPEN BROWSERS ALSO :(
BrowserConfig.releaseResources(this.driver);
}
}
LinkStatsStep.java
#Ignore
public class LinkStatsStep {
private WebDriver driver;
#Before
public void setup() {
System.out.println("Into the setup method of LinkStatsStep...");
this.driver = BrowserConfig.getIEWebDriver();
}
#Given("^The user is on the Link Statistics page$")
public void onPage() {
System.out.println("The user is on the Link Statistics page");
}
#When("^The user does a search$")
public void clickLinks() {
System.out.println("The user does a search");
}
#Then("^The user is displayed search result$")
public void validate() {
System.out.println("The user is displayed search result");
}
#After
public void cleanUp() {
System.out.println("Into the cleanUp method of LinkStatsStep...");
BrowserConfig.releaseResources(this.driver);
}
}
TestRunner.java
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = {"pretty", "json:target/cucumber-reports/cucumber.json"},
features = {"src/test/resources/features"})
public class TestRunner extends ApplicationTests {
}
BrowserConfig.java
public class BrowserConfig {
private static final String IE_DRIVER_EXE = "drivers/IEDriverServer.exe";
private static final String WEBDRIVER_IE_DRIVER = "webdriver.ie.driver";
private static final String BASE_URL = "https://www.google.com";
public static WebDriver getIEWebDriver() {
String filePath = ClassLoader.getSystemClassLoader().getResource(IE_DRIVER_EXE).getFile();
System.setProperty(WEBDRIVER_IE_DRIVER, filePath);
InternetExplorerOptions options = new InternetExplorerOptions().requireWindowFocus();
options.setCapability(INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
options.setCapability(ENABLE_ELEMENT_CACHE_CLEANUP, true);
options.setCapability(IE_ENSURE_CLEAN_SESSION, true);
options.setCapability(ACCEPT_SSL_CERTS, true);
options.setCapability("nativeEvents", false);
options.setCapability(INITIAL_BROWSER_URL, BASE_URL);
System.out.println("Initializing IE Driver now...........");
WebDriver driver = new InternetExplorerDriver(options);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
return driver;
}
public static void releaseResources(WebDriver driver) {
System.out.println("Releasing resources now.....");
if (null != driver) {
driver.close();
driver.quit(); //CLOSES ALL THE OPEN BROWSER SESSIONS LEAVING OTHER STEP EXECUTIONS INCOMPLETE
}
}
}
help.feature
Feature: Check that the user is able to navigate to Help page
Scenario:
Given The user is on the Help page
When The user clicks on the links within the Help page
Then The user is navigated to that section
link-stats.feature
Feature: Check that the user is able to navigate to Link Statistics page
Scenario:
Given The user is on the Link Statistics page
When The user does a search
Then The user is displayed search result
System.outs
Initializing IE Driver now...........
Listening on port 47613
Into the setup method of LinkStatsStep...
Initializing IE Driver now...........
Listening on port 5009
The user is on the Help page
The user clicks on the links within the Help page
The user is navigated to that section
Into the cleanUp method of HelpStep...
Releasing resources now.....
Into the cleanUp method of LinkStatsStep...
Releasing resources now.....
Into the setup method of HelpStep...
Initializing IE Driver now...........
Listening on port 17291
Into the setup method of LinkStatsStep...
Initializing IE Driver now...........
Listening on port 23793
The user is on the Link Statistics page
The user does a search
The user is displayed search result
Into the cleanUp method of HelpStep...
Releasing resources now.....
Into the cleanUp method of LinkStatsStep...
Releasing resources now.....
Looking at your code it would appear to be correct.
Calling quit should close all open windows associated with that webdriver session. It should not close windows of other webdriver sessions. So I think you are facing a problem in the IEDriverServer.
If this is the case and if you are running your tests in a JVM that shuts down after all tests have been executed. Then as a work around you can use shut down hooks to call quite and close all web driver sessions. For example:
private static final Thread CLOSE_THREAD = new Thread() {
#Override
public void run() {
// Start a new webdriver to call quit on
// For IE this will terminate all webdriver sessions
getIEWebDriver().quit();
}
};
static {
Runtime.getRuntime().addShutdownHook(CLOSE_THREAD);
}
Posted the answer here as this question is more or less similar earlier one.
https://stackoverflow.com/a/55836832/2325154
It is because driver management not done properly. I would suggest to use qaf which does driver and resource management. With QAF your step file will look like below:
public class HelpStep {
//setup or tear-down not required here...
#Given("^The user is on the Help page$")
public void onPage() {
//you can access driver any where like below:
//WebDriver driver = new WebDriverTestBase().getDriver();
System.out.println("The user is on the Help page");
}
#When("^The user clicks on the links within the Help page$")
public void clickLinks() {
System.out.println("The user clicks on the links within the Help page");
}
#Then("^The user is navigated to that section$")
public void validate() {
System.out.println("The user is navigated to that section");
}
}
To access driver object any where in the code you can get it from test base.
WebDriver driver = new WebDriverTestBase().getDriver();
Below are examples of interacting with element anywhere in the code:
Using findBy
driver.findElement("name=q").click();
Using element factory
import static com.qmetry.qaf.automation.ui.webdriver.ElementFactory.$;
...
$("name=q").click();
Using inbuilt step library
import static com.qmetry.qaf.automation.step.CommonStep.*;
...
click("name=q");
in example above name=q is element locator using name as locator strategy, which will automatically converted to By.name.
LinkStatsStep
import static com.qmetry.qaf.automation.step.CommonStep.*;
...
public class LinkStatsStep {
#Given("^The user is on the Link Statistics page$")
public void onPage() {
get("/");
}
#When("^The user does a search$")
public void clickLinks() {
System.out.println("The user does a search");
click("elementlocator");
//$("elementlocator").click();
}
#Then("^The user is displayed search result$")
public void validate() {
verifyLinkWithPartialTextPresent("link text");
//$("partialLink=link text").verifyPresent();
}
}
Your gherkin file will remain same. To run your gherkin file use GherkinScenarioFactory
You can specify browser to use using driver.name property. You don't need to write code for creating or tearing down driver. You can set behavior of driver session by using selenium.singletone property.
#this will tear down driver after each testcase/scenario
selenium.singletone=method
#this will tear down driver after each xml test node in configuration file
selenium.singletone=test
#this will tear down driver after each xml test node in configuration file and will reuse same driver session for testcases/scenario configured under same xml test node.
selenium.singletone=test
#this will tear down driver after each xml suite node in configuration file.
selenium.singletone=suite
I'm writing a Selenium test script for my website. Firefox opens multiple empty pages while Selenium test running and test fails to identify elements in my script. Im using 47.0.1 firefox and selenium-server-standalone-3.0.0-beta3.
Here is my Main activity.
public class Main {
public static void main(String[] args) throws InterruptedException{
// Print the Execution Date
GetExecutionDate getExDate = new GetExecutionDate();
getExDate.getExecutionDate();
MainFlow mainFl = new MainFlow();
mainFl.mainFlow();
}
}
Here is my MainFlow.java file.
public class MainFlow {
public void mainFlow() throws InterruptedException{
System.setProperty("webdriver.firefox.marionette","D:\\My Work\\Setup\\JAR\\geckodriver.exe");
// Initialize Firefox Profile
ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("Myyy");
WebDriver driver = new FirefoxDriver(myprofile);
//Puts an Implicit wait, Will wait for 25 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
//Launch Ayubo.lk site
driver.navigate().to("my site");
//Maximize the browser
driver.manage().window().maximize();
Thread.sleep(3000);
driver.findElement(By.xpath("//div[#id='navbar-main']/ul/li[5]/a")).click();
System.out.println("User clicked My Account button");
driver.findElement(By.xpath("//div[#id='navbar-main']/ul/li[5]/ul/li/a")).click();
System.out.println("User clicked Login button");
Thread.sleep(3000);
// Enter User name
driver.findElement(By.name("email")).sendKeys("dd#hh.com");
System.out.println("User enter username");
// Enter Password
driver.findElement(By.name("password")).sendKeys("12345");
System.out.println("User enter password");
Thread.sleep(3000);
// Click Login Button
driver.findElement(By.xpath("//form[#id='loginform']/div[8]/button")).click();
System.out.println("User clicked Login button");
Thread.sleep(5000);
// Click Book now Button
driver.findElement(By.xpath("//div[#id='navbar-main']/ul/li[2]/a/span")).click();
System.out.println("User clicked Book now button");
Thread.sleep(3000);
// Click Book hotels button
driver.findElement(By.xpath("//div[#id='navbar-main']/ul/li[2]/ul/li/a")).click();
System.out.println("User clicked Book Hotels button");
}
}
But, when the script is running it opens up different empty pages and script fails
Found the answer here. This is because of compatibility issue with the browser and Selenium libs. Selenium libs Im using supports Firefox version different firefox versions, and for 12 I have to upgrade your Selenium libs.
However, if I set up to run using Microsoft Edge the test completes and i can see the user just created in the list. Here is my code. Very confused.
As you can see all I change to run for Microsoft Edge is un-comment the setProperty line and then change the FirefoxDriver to EdgeDriver. When I do that as I said the script runs and upon completion I log in and can see the user in the list while when using this code I cannot see the user.
public static void main (String[] args) throws InterruptedException {
// System.setProperty("webdriver.edge.driver", "/Program Files (x86)/Microsoft Web Driver/MicrosoftWebDriver.exe");
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
baseUrl = "http://briotest.brio.viddler.com/";
firstName = "Sam";
lastName = "Bradford";
email = "sbradford#mail.com";
password = "Sooners1!";
test();
}
public static void test() throws InterruptedException {
// get to login page and enter credentials
driver.get(baseUrl + "/users/login");
driver.findElement(By.name("email_address")).clear();
driver.findElement(By.name("email_address")).sendKeys("jfayefrank#yahoo.com");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("*********");
driver.findElement(By.cssSelector("button.button")).click();
// Now on the assets view page. Go to Users and select Create
driver.findElement(By.xpath("/html/body/header/div[2]/nav/div/ul[1]/li[6]/a")).click(); // Users tab
driver.findElement(By.linkText("Create")).click();
// Enter new users credentials and submit
driver.findElement(By.id("email")).clear();
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("first_name")).clear();
driver.findElement(By.name("first_name")).sendKeys(firstName);
driver.findElement(By.name("last_name")).clear();
driver.findElement(By.name("last_name")).sendKeys(lastName);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(email);
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys(password);
try {
Thread.sleep(5000);
}
catch (Exception e) {
System.out.println("Could not perform pause");
}
// driver.findElement(By.cssSelector("input.button")).click();
driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/input[2]")).click();
System.out.println ("User created!!!");
}
Problem solved. Thanks to a coworker my problem is resolved. Apparently since Firefox was not maximized the Submit button was not really selected even though it appeared to do the action. Once I added driver.manage().window().maximize(); my users were now visible in the list. Did I mention the coworker was an intern...
Hi I am facing this issue, Below is a code which i had generated using Selenium IDE, Basically i am trying to access a career portal of the particular website below and for the Jobposting QA specialist, I was experimenting to auto complete the application using Selenium.
1) I am not able to replicate the code working in webdriver despite adding the code under proper class and importing all the necessary packages.
2) On running it as a TestNG test, i have a failure showing Unable to find Element.
3) The link to the QA specialist is not being detected by the driver either if i give it as identify By.link text or By.xpath.
4) please guide me where i am making mistake.
5) I am a beginer to Selenium
public class Application {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.saymedia.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testApplication() throws Exception {
driver.get(baseUrl + "/jobs");
driver.findElement(By.linkText("QA Specialist")).click();
driver.findElement(By.linkText("Apply Now")).click();
driver.findElement(By.linkText("Send Application")).click();
}
Your elements are inside of an iframe. Selenium only interacts with elements in the current frame. Any element within a child frame cannot be interacted with until you switch into that frame. You can switch by using switchTo().frame():
driver.get(baseUrl + "/jobs");
driver.switchTo().frame("jobviteframe");
driver.findElement(By.linkText("QA Specialist")).click();
driver.findElement(By.linkText("Apply Now")).click();
driver.findElement(By.linkText("Send Application")).click();
The arguments for frame() are
number from 0
id of the frame
the webelement rerference of the frame
When done in the iframe, use the following to exit back to the top of the document:
driver.switchTo().defaultContent();
I am using HtmlUnit headless browser to browse this webpage (you can see the webpage to have a better understanding of the problem).
I have set the select's value to "1"
by the following commands
final WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_7);
try {
// Configuring the webClient
webClient.setJavaScriptEnabled(true);
webClient.setThrowExceptionOnScriptError(false);
webClient.setCssEnabled(true);
webClient.setUseInsecureSSL(true);
webClient.setRedirectEnabled(true);
webClient.setActiveXNative(true);
webClient.setAppletEnabled(true);
webClient.setPrintContentOnFailingStatusCode(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
// Adding listeners
webClient.addWebWindowListener(new com.gargoylesoftware.htmlunit.WebWindowListener() {
public void webWindowOpened(WebWindowEvent event) {
numberOfWebWindowOpened++;
System.out.println("Number of opened WebWindow: " + numberOfWebWindowOpened);
}
public void webWindowContentChanged(WebWindowEvent event) {
}
public void webWindowClosed(WebWindowEvent event) {
numberOfWebWindowClosed++;
System.out.println("Number of closed WebWindow: " + numberOfWebWindowClosed);
}
});
webClient.setWebConnection(new HttpWebConnection(webClient) {
public WebResponse getResponse(WebRequestSettings settings) throws IOException {
System.out.println(settings.getUrl());
return super.getResponse(settings);
}
});
CookieManager cm = new CookieManager();
webClient.setCookieManager(cm);
HtmlPage page = webClient.getPage("http://www.ticketmaster.com/event/0B004354D90759FD?artistid=1073053&majorcatid=10002&minorcatid=207");
HtmlSelect select = (HtmlSelect) page.getElementById("quantity_select");
select.setSelectedAttribute("1", true);
and then clicked on the following button
by the following commands
HtmlButtonInput button = (HtmlButtonInput) page.getElementById("find_tickets_button");
HtmlPage captchaPage = button.click();
Thread.sleep(60*1000);
System.out.println("======captcha page=======");
System.out.println(captchaPage.asXml());
but even after clicking on the button and waiting for 60 seconds through the Thread.sleep() method, I am getting the same HtmlPage.
But when I do the same thing through real browser then I get the page that contains CAPTCHA.
I think I am missing something in the htmlunit.
Q1. Why am I not getting the same page (that contains CAPTCHA) through htmlunit's browser?
The web form on that page requires the quantity_select drop-down to be filled in. You're attempting to do that in your code by assuming the drop-down is a select element. However, it's no longer a select element. Try using Firebug to inspect the drop-down and you'll see that JavaScript has replaced the select with a complex set of nested div elements.
If you figure out how to emulate each user click on the divs for that unusual drop-down then you should be able to submit the form.