Error locating the element in selenium2 - selenium

I am using selenium2.0 with testNG. While on using XPATH or CSS for element to locate its shows error “unable to locate the element” .
I have programmed in Java as
below:
public class mytest {
public static WebDriver driver;
public Alert alert;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
driver=new FirefoxDriver();
driver.get("http://localhost:4503/xyz.html");
}
public static void clickButton(WebDriver driver, String identifyBy, String locator){
if (identifyBy.equalsIgnoreCase("xpath")){
driver.findElement(By.xpath(locator)).click();
}else if (identifyBy.equalsIgnoreCase("id")){
driver.findElement(By.id(locator)).click();
}else if (identifyBy.equalsIgnoreCase("name")){
driver.findElement(By.name(locator)).click();
}
}
public static void typeinEditbox(WebDriver driver, String identifyBy, String locator, String valuetoType){
if (identifyBy.equalsIgnoreCase("xpath")){
driver.findElement(By.xpath(locator)).sendKeys(valuetoType);
}else if (identifyBy.equalsIgnoreCase("id")){
driver.findElement(By.id(locator)).sendKeys(valuetoType);
}else if (identifyBy.equalsIgnoreCase("name")){
driver.findElement(By.name(locator)).sendKeys(valuetoType);
}
}
public static void openApplication(WebDriver driver, String url) {
driver.get(url);
}
#Test
public void testAcrolinxApplication() throws InterruptedException {
openApplication(driver,"http://xyz.com");
typeinEditbox(driver,"name","p_user","xxx");
typeinEditbox(driver,"name","p_pas","yyy");
clickButton(driver,"id","input-submit");
/*Up to this its working fine …..
At below line this throws error could not locate the xpath element "//a[#id='cq-gen100']/em/span/span" BUT THIS IS WOKING FINE IN Selenium1.0 api that is with
selenium.click("//a[#id='cq-gen100']/em/span/span"); */
driver.findElement(By.xpath("//a[#id='cq-gen100']/em/span/span")).click();
}
}
Please help me on this.
Thanks in advance…

Make Sure XPath/CSS Query is Correct
Download something like Firefinder or anything else where you can test the XPath query directly on the page. Once you know for sure that your query is correct, then you can narrow down the problem in Selenium.
Narrow Down the Problem in Selenium
For example, if your query "//a[#id='cq-gen100']/em/span/span" is not working, try the base of the query and see if Selenium finds it (don't worry about click for now). Increment from there until the error appears again.
Example:
driver.findElement(By.xpath("//a[#id='cq-gen100']"); //works?
driver.findElement(By.xpath("//a[#id='cq-gen100']/em"); //works?
driver.findElement(By.xpath("//a[#id='cq-gen100']/em/span"); //works?
//etc

I have used
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
to wait for some time, Noew its working.

Related

how to declare Explicit wait in TestNG framework where script is written for multiple browsers?

I am working on a selenium script where I am using explicit wait. I have a script where I have three methods to invoke IE,FireFox and Chrome browsers.
I will be executing script for one browser at a time. now the question is how should I declare the wait (explicitly). I can see two following options.
1. Create an object of WebDriverWait class Globally--- In this scenario web driver throws the exception as there is no object created for the browser class(in this case FireFoxDriver()).
2.Create an object of WebDriverWait class locally in any method-- In this scenario wait works perfectly but in case i have to use the wait again for any other element. it would ask you to create object of WebDriverWait class locally again(which is something i want to avoid)..
In Short. I just want to create object of WebDriverWait class onle once in the code. How can i do it for the below mentioned code???
following is the code..
public class para {
WebDriver driver;
#BeforeClass
void InvokeFF() {
System.setProperty("webdriver.gecko.driver",
"C:/Users/Vinay/workspace_n/EGuru/drivers/geckodriver.exe");
driver = new FirefoxDriver();
// driver.get("http://seleniumpractise.blogspot.in/2016/08/bootstrap-dropdown-example-for-selenium.html");
System.out.println("Firefox invoked");
System.out.println("Firefox thread:" + Thread.currentThread().getId());
}
#BeforeClass(enabled = false)
void InvokeIE() {
System.setProperty("webdriver.ie.driver",
"C:/Users/Vinay/workspace_n/EGuru/drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
System.out.println("Internet Explorer invoked");
System.out.println("IE thread:" + Thread.currentThread().getId());
}
#BeforeClass(enabled = false)
void InvokeGC() {
System.setProperty("webdriver.chrome.driver",
"C:/Users/Vinay/workspace_n/EGuru/drivers/chromedriver.exe");
driver = new ChromeDriver();
// driver.get("http://www.seleniumeasy.com");
System.out.println("Chrome invoked");
System.out.println("Chrome thread:" + Thread.currentThread().getId());
}
#Test
void Auto() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 20);
driver.get("file:///C:/Users/Vinay/Desktop/Upload1.html");
wait.until(ExpectedConditions.visibilityOfElementLocated(By
.xpath(".//*[#id='1']")));
driver.findElement(By.xpath(".//*[#id='1']")).click();
Runtime.getRuntime().exec("C:\\Users\\Vinay\\Desktop\\AutoUpload.exe");
}
}
I think what you're looking for is an implicit wait, not an explicit wait. This can be accomplished by using the line of code below after your driver has been created (using whichever driver it needs)
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Obviously change the 10 seconds to whatever default timeout you want.
If you want to put explicitly wait please use the please code :
public static WebDriverWait wait = new WebDriverWait(driver, 10);
public static void wait(String waitElement)
{
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(waitElement)));
}
Worked for me !

in Selenium webdriver 2 testng, difficult to fetch the hardcoded elements in application?

In selenium Webdriver testng, i have hardcoded some elements in my program but the testng is not finding the element.so i gave thread.sleep but in case its working and in other case not working.i gave explicit function also.TO find Element , i written the method called findelement
public findElement(String Locator)
{
locator(Locator);
identifyBy (identifier);
}
public static void locator(String locator) {
}
This is what i done in my selenium framework.please help me to fetch the data.
public static void waitForElementToAppear(WebDriver driver, By selector, long timeOutInSeconds) {
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(selector));
}

Issue with methods ( Test cases ) in Selenium Webdriver

I am new to Selenium, While practicing I come up with one issue, I am doing testing for my own application which has been deployed in tomcat server. So after opening my application I am testing validations in one method and page change in one method. Now My point is I am doing both testing for my both methods at same page.
Why do I need to write same code both methods,
driver.get("http://localhost:8070/");
driver.findElement(By.xpath("//div[#id='actions']/div[2]/a/span")).click();
driver.findElement(By.linkText("/ReportGenerator")).click();
How can I directly perform operations, If I remove above two lines in my second method It is getting failed. How to solve this?
#Test
public void analysisValidation()
{
driver.get("http://localhost:8070/");
driver.findElement(By.xpath("//div[#id='actions']/div[2]/a/span")).click();
driver.findElement(By.linkText("/ReportGenerator")).click();
driver.findElement(By.id("Analysis")).click();
WebElement webElement = driver.findElement(By.id("modelForm.errors"));
String alertMsg = webElement.getText();
System.out.println(alertMsg);
Assert.assertEquals("Please select a Survey Id to perform Aggregate Analysis", alertMsg);
}
#Test
public void testAnalysisPage()
{
driver.get("http://localhost:8070/");
driver.findElement(By.xpath("//div[#id='actions']/div[2]/a/span")).click();
driver.findElement(By.linkText("/ReportGenerator")).click();
new Select(driver.findElement(By.id("surveyId"))).selectByVisibleText("Apollo");
driver.findElement(By.id("Analysis")).click();
System.out.println(driver.getTitle());
String pageTitle = driver.getTitle();
Assert.assertEquals("My JSP 'analysis.jsp' starting page", pageTitle);
}
How can I directly perform operations, If I remove above two lines in
my second method It is getting failed. How to solve this
The tests fail because each #Test test is executed independently. The code you remove is needed to initialize the driver and load the page.
You can fix this as follows:
Create a function, setUp() with the #beforemethod annotation. Populate it with the driver initialization and loading-page calls.
Create a function, teardown() with the #AfterMethod annotation. Populate it with the driver cleanup calls.
For example, here is some pseudocode (modify this as per taste)
#BeforeMethod
public void setUp() throws Exception {
driver.get("http://localhost:8070/");
driver.findElement(By.xpath("//div[#id='actions']/div[2]/a/span")).click();
driver.findElement(By.linkText("/ReportGenerator")).click();
}
#AfterMethod
public void teardown() throws Exception {
driver.quit()
}
The advantage of the #BeforeMethod and #AfterMethod annotations is that the code will be run before / after each #Test method executes. You can therefore avoid having to duplicate your code.

restore current sections for next test case in Selenium scripts

I am using selwnium web driver. When I am using selenium and nunit to run my test cases I find that every time a test case starts it open a new page and when its done the mew page will be destoryed. Therefore I have to open new page and login in every test case.
I want to have my test cases share one single webpage so that they can be performed in sequence.
Is a selenium limitation, or is it a way to implement it?
Thank you!
Try to declare Webdriver instance variable as static inside your test class and initialize only once. Your behavior is because different webdriver instances does not share the same session, so therefore you have always to login into desired page.
You probably using #Before , #After annotation.
Try use #BeforeClass, #AfterClass instead. e.g:
....
static WebDriver driver;
#BeforeClass
public static void firefoxSetUp() throws MalformedURLException {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().window().setSize(new Dimension(1920, 1080));
}
#Before
public void homePageRefresh() throws IOException {
driver.manage().deleteAllCookies();
driver.get(propertyKeysLoader("login.base.url"));
}
#AfterClass
public static void closeFirefox(){
driver.quit();
}
.....

Is it possible to start few seleniums for one selenium server?

Is this valid code?
selenium = new DefaultSelenium("localhost", 4444, "*iehta",
"http://www.google.com/");
selenium.start();
...
selenium.stop();
...
selenium.start();
...
selenium.stop();
There's nothing wrong with having multiple browsers open (what you call "seleniums"). In fact, it's the only way you can test certain applications. Imagine an application that has an administrative UI and an end-user UI, where you make changes on the admin side and verify their effects on the user side. You can either write your test to jump back and forth between the two on the same browser session, or you can open two browsers, one for each aspect of the application. The former is the usual technique, but the latter is much cleaner.
And why do you think it shouldn't be safe? unless it works ok it's fine, If it doesn't than recreate the DefaultSelenium object again, it won't slow down your code anyway
You should usually keep start() and stop() as you set up and tear down methods. While using TestNG you can annonate then with #BeforeClass and #AfterClass annonations. Hence browser would be launched and shut down only before and after a test method in a class.
b/w did you support Selenium Proposal on area51 - http://area51.stackexchange.com/proposals/4693/selenium
This proposal is backed by SeleniumHQ and we need more users to commit to it to make it see day of light.
That was my fault.
Unexpected behaviour caused by this code and occurs because I stop selenium two times (selenium object never become null):
public class SeleniumController {
private static Selenium selenium;
public static Selenium startNewSelenium(){
// if already exists stop it and replace with new one
if(selenium != null){
selenium.stop();
}
selenium = createNewSelenium(getCurContext());
return selenium;
}
public static void stopSelenium() {
if(selenium != null){
selenium.stop();
}
}
private static Selenium createNewSelenium(TestContext testContext){
TestProperties testProps = new TestProperties(testContext);
ExtendedSelenium selenium = new ExtendedSelenium("localhost", RemoteControlConfiguration.DEFAULT_PORT,
testProps.getBrowser(), testProps.getServerUrl());
selenium.start();
selenium.useXpathLibrary("javascript-xpath");
selenium.allowNativeXpath("false");
return selenium;
}
}
The correct class code is:
public class SeleniumController {
private static Selenium selenium;
public static Selenium startNewSelenium(){
// if already exists stop it and replace with new one
stopSelenium();
selenium = createNewSelenium(getCurContext());
return selenium;
}
public static void stopSelenium() {
if(selenium != null){
selenium.stop();
selenium = null;
}
}
private static Selenium createNewSelenium(TestContext testContext){
TestProperties testProps = new TestProperties(testContext);
ExtendedSelenium selenium = new ExtendedSelenium("localhost", RemoteControlConfiguration.DEFAULT_PORT,
testProps.getBrowser(), testProps.getServerUrl());
selenium.start();
selenium.useXpathLibrary("javascript-xpath");
selenium.allowNativeXpath("false");
return selenium;
}
}