java.lang.NullPointerException using static WebDriver instance - java

I want to separate my code in to smaller functions.
But had an issue as driver was not available to all functions.
So i declared it as a constant (or is there a better way of doing this ?)
but in 3rd function it is failing on line :
Select dropdown_finance_product = new Select(driver.findElement(By.xpath("//select[#id='ResultsNumber']")));
Here is the console message :
Exception in thread "main" java.lang.NullPointerException
at Scraping.scrapeit.fetch_urls(scrapeit.java:49)
at Scraping.scrapeit.main(scrapeit.java:24)
Code :
package Scraping;
import java.io.IOException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import tools.Xls_Reader;
public class scrapeit {
static WebDriver driver;
public static void main(String[] args) throws IOException {
start_browser();
fetch_urls();
read_excel();
}
public static void start_browser() {
System.setProperty("webdriver.chrome.driver", "C:\\Chrome Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.get("http://www.example.com/search/items/new/");
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.titleContains("New items));
}
public static void fetch_urls() {
Select dropdown_finance_product = new Select(driver.findElement(By.xpath("//select[#id='ResultsNumber']")));
dropdown_finance_product.selectByVisibleText("100");
System.out.println("Selected 100 Items Dropdown");
// Open Excel and write urls back
Xls_Reader datatable = new Xls_Reader("C:\\scrape.xlsx");
List<WebElement> num_items = driver.findElements(
By.xpath("//a [contains(#href,'http://www.example.com/search/items/new/latest-')] "));
for (int i = 0; i < num_items.size(); i++) {
System.out.println("How many items on page = : " + num_items.size() + " counter = " + i);
String link = num_items.get(i).getAttribute("href");
datatable.setCellData("New", "URL", i + 2, link);
System.out.println("URL : " + link);
}
}
public static void read_excel() {
// Read in url and process...
Xls_Reader datatable = new Xls_Reader("C:\\scrape.xlsx");
int r = datatable.getRowCount("URL");
int c = datatable.getColumnCount("URL");
System.out.println("num of rows = " + r + " num of cols = " + c);
}
}

The error says it all :
Exception in thread "main" java.lang.NullPointerException
In class scrapeit you have already declared webdriver as an instance of WebDriver as static as follows :
static WebDriver driver;
But then you are again initializing another driver as a new instance of WebDriver as follows :
WebDriver driver = new ChromeDriver();
Hence you see java.lang.NullPointerException
Solution
A quick solution will instead of creating another instance of the WebDriver you need to use the static instance of WebDriver. So you need to remove WebDriver from WebDriver driver = new ChromeDriver(); as follows :
driver = new ChromeDriver();

Related

How to access multiple tab with URL + variable in Java Selenium?

I need to open over 100 pages (https://same URL/"different page") and I want to use for loop with variable to open a certain amount of them at once.
I wrote below code in Java selenium but got an error: javascript error: missing ) after argument list
Could someone help me to figure out where went wrong please? Thank you.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
public class multibrowser {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"E:\\Selenium\\chromedriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.abc/";
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.location = \'" + url + "\'");
new Click().clickElement(driver.findElement(By.cssSelector("span[title=123']")));
try {
Thread.sleep(15000);
} catch (InterruptedException ie) {
System.out.println("Loading time longer than 15 seconds");
}
// create list
List<String> crunchifyList = new ArrayList<String>();
// add 2 different values to list
crunchifyList.add("123");
crunchifyList.add("456");
//For loop
for (int i = 0; i < crunchifyList.size(); i++) {
js.executeScript("window.open('https://www.abc/' + crunchifyList.get(i) +', '_blank');");
}
}
}
You missed quotes(""), should be:
js.executeScript("window.open('https://www.abc/'" + crunchifyList.get(i) + "', '_blank');");

I can not passing variable to Main method (Cucumber)

I had tried to create method and call it from another file to the main class but It won't work the error message said "java.lang.NullPointerException"
Main.class
Keywords kw = new Keywords();
#When("^gmailDD$")
public void gmailDD() throws Throwable{
WebDriverWait wait5s = new WebDriverWait(driver, 5);
String regis = "/html/body/div[2]/div[1]/div[5]/ul[1]/li[3]/a";
String dd = "/html/body/div[1]/div/footer/div/div/div[1]";
String empty = "/html/body/div[1]/div/footer";
kw.clickbyxpath(regis);
String handle= driver.getWindowHandle();
System.out.println(handle);
// Store and Print the name of all the windows open
Set handles = driver.getWindowHandles();
System.out.println("Log window id: "+handles);
driver.switchTo().window("6442450949");
kw.clickbyxpath(empty);
kw.clickbyxpath(dd);
}`
Method.class
WebDriver saddriver;
public void clickbyxpath (String xpathvalue) throws InterruptedException, IOException
{
WebDriverWait sad = new WebDriverWait(saddriver, 10);
//To wait for element visible
System.out.println(xpathvalue);
String x = xpathvalue;
sad.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x)));
wowdriver.findElement(By.xpath(x)).click();
}
I had tried to do the same coding in the same file, It has no problem but when I move Method.class to the new file, error message said "java.lang.NullPointerException" but I can get "xpathvalue" value.
This Error occur because of it will not able to find your driver instance.
refer below code snippet. this is not cucumber example but you can get idea by this.
Method.class
package testing.framework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Method {
public WebDriver driver;
WebElement _clickForSearch;
public Method(WebDriver driver) {
this.driver = driver;
}
public Method clickByXpath(String xpathValues) {
WebDriverWait wait = new WebDriverWait(driver, 10);
_clickForSearch = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpathValues)));
_clickForSearch.click();
return this;
}
}
Testing.class
package testing.framework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Testing {
public static WebDriver driver;
public static void main(String[] args) {
getWebDriver();
String xpathValues= "//div[#class='FPdoLc VlcLAe']//input[#name='btnK']";
Method m1 = new Method(driver);
m1.clickByXpath(xpathValues);
}
public static void getWebDriver() {
System.setProperty("webdriver.chrome.driver", "Your chrome driver path");
driver = new ChromeDriver();
driver.get("https://www.google.com");
}
}
You need to pass your driver instance to another.
So I would suggest you take the webdriver wait out of your method and instantiate it when instantiating your webdriver. I would then create methods like so:
Driver class
private final String USER_DIRECTORY = System.getProperty("user.dir");
private final int GLOBAL_TIMEOUT = 30;
private WebDriver webDriver;
private WebDriverWait webDriverWait;
public Driver(String browserName) {
this.browserName = browserName;
System.out.println(browserName);
switch (this.browserName.toUpperCase()) {
case "CHROME":
initializeChromeDriver();
break;
}
}
private void initializeChromeDriver() {
System.setProperty("webdriver.chrome.driver", USER_DIRECTORY.concat("\\drivers\\chromedriver.exe"));
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
webDriverWait = new WebDriverWait(webDriver, GLOBAL_TIMEOUT);
}
Click method
public void buttonClickByXpath(String xpath) {
try {
WaitForPreseneOfElement(xpath);
webDriver.findElement(By.xpath(xpath)).click();
} catch (Exception e) {
takeScreenshot();
AllureLog("Failed to click on the button object. Please check your xpath. | xpath used = " + xpath + "");
Assert.fail();
}
}
Test Class
Import your driver class
import Base.Driver;
Then you would need declair your driver class like so:
Driver driver;
Now you will have access to your method using
driver.buttonClickByXpath(//YourXpathHere)
The problem is "Method m1 = new Method(driver);" keyword,
I had coded this line outside the main method.
thank you very much, Sir

Using eval function to create driver object in Selenium

I'm trying to use eval function to create a driver object in selenium. But am getting an error - "ReferenceError: "FirefoxDriver" is not defined". At line - "Object objBrow = objJSEngine.eval(strTxt);"
As I want to put the string -driver type in property file eventually. Below is the code.
Could anyone help me on this. Thanks.
package septmeber;
import java.util.concurrent.TimeUnit;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Initial {
public static void main(String arrParm[]) throws ScriptException
{
//Declare Variables
String strClassName;
By objBYTwiter;
WebElement objTwitterTag;
String strBorwserType;
String strTxt;
String strURL;
objBYTwiter = null;
objTwitterTag = null;
strClassName = "span[class = 'at16nc at300bs at15nc at15t_twitter at16t_twitter']";
strBorwserType = "FirefoxDriver";
strURL = "http://www.tutorialspoint.com/java/java_enumeration_interface.htm";
//Create Driver object
ScriptEngineManager objManager = new ScriptEngineManager();
ScriptEngine objJSEngine = objManager.getEngineByName("js");
strTxt = "new"+"\t "+strBorwserType+"();" ;
Object objBrow = objJSEngine.eval(strTxt);
WebDriver objBrowser = (WebDriver)objBrow;
//Launch the application
objBrowser.get(strURL);
objBrowser.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
System.out.println("Application launched");
objBrowser.manage().window().maximize();
//Click Twitter Link
objBYTwiter = By.cssSelector(strClassName);
objTwitterTag = objBrowser.findElement(objBYTwiter);
objTwitterTag.click();
}
}
What you are asking is not possible.
You can create a method something like:
WebDriver selenium;
public void setSelenium(String driver) {
if (driver.equals("firefox")) {
selenium = new FirefoxDriver();
} else if (driver.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "path to chrome");
selenium = new ChromeDriver();
} // define more as you need
}
Then you can call this method with something like:
setSelenium(System.getenv("browser"));
Where in your environment you first set the variable "browser" to whichever you want to run. You can also get this value from something else, like a file.

how to locate an element of a page after new data loaded on the same page in selenium webdriver

I am trying to copy the table data of the html page which is loaded on the same page after clicking on the 'Get Table' button on the previous page. However, as the page url is not changing I am getting exception of 'No such element' when trying to locate new elements on newly loaded page. Following is the code I tried:
package com.test.selenium;
import java.util.List;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.Test;
import junit.framework.TestSuite;
public class Example1{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Java Stuff\\Selenium Tutorial\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.oanda.com/currency/table");
WebElement date = driver.findElement(By.name("date"));
date.sendKeys("12/04/10");
WebElement date_frmt = driver.findElement(By.name("date_fmt"));
date_frmt.sendKeys("yy/mm/dd");
WebElement curr = driver.findElement(By.name("exch"));
curr.sendKeys("US Dollar.USD");
Select sel = new Select(driver.findElement(By.name("Currency")));
sel.deselectAll();
List lsize = sel.getOptions();
int count = lsize.size();
for(int j=0;j<count;j++)
{
String lvalue = sel.getOptions().get(j).getText();
sel.selectByVisibleText(lvalue);
}
WebElement crr = driver.findElement(By.name("dest"));
crr.click();
driver.getCurrentUrl();
String table = driver.findElement(By.id("converter_table")).getText();
System.out.println(table);
}
}
According to exception it seems that element not exists on the page, or smth wrong with you xpath. Why you use xpath?! Try css selectors (they are more powerful and stable) =) e.g.
driver.findElement(By.css("#converter_table"));
P.S. if you want to verify that your selector is correct (no matter xpath or css) use dev console in browser (e.g. for css enter $("#converter_table") in console, and if element exists (and this id has no type in the name) then you'll see what this selector will return)). For xpath use $x("xpath")
UPDATE:
Simple solution i think is to add some method which will wait for element, some period of time. Below sample code in C# (test with wait method)
private IWebDriver driver;
[SetUp]
public void SetUp()
{
// Here i just create browser as you (firefox, chrome etc);
driver = CreateBrowser("http://www.oanda.com/currency/table");
}
[TearDown]
public void TearDown()
{
driver.Dispose();
}
[Test]
public void PortTest()
{
var dateElement = driver.FindElement(By.Name("date"));
dateElement.SendKeys("12/04/10");
var dateFrmt = driver.FindElement(By.Name("date_fmt"));
dateFrmt.SendKeys("yy/mm/dd");
var curr = driver.FindElement(By.Name("exch"));
curr.SendKeys("US Dollar.USD");
var crr = driver.FindElement(By.Name("dest"));
crr.Click();
WaitUntilLoad();
var table = driver.FindElement(By.Id("converter_table"));
Console.Write("the text is " + table.Text);
}
public void WaitUntilLoad()
{
int repetitionCount = 0;
bool isLoaded = false;
while (!isLoaded)
{
var table = driver.FindElements(By.Id("converter_table")).Count;
if (table > 0 )
isLoaded = true;
Thread.Sleep(250);
repetitionCount++;
Console.WriteLine("Searching again for element");
if (repetitionCount > 25) break;
}
}
you get NoSuchElement because your xpath seems wrong
try
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//*[#id='content_section']/table")));
String table = driver.findElement(By.xpath(".//*[#id='content_section']/table")).getText();

Element not found error while selecting dropdown in Java selenium

Here is the code i have written
I get the below error when the weblist selects second user from drop down the Error is
Caused by Element not found in the cache - perhaps the page has changed since it was looked up
The code is
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class SimpleBrowseroperation
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
//WebDriver driver = new InternetExplorerDriver();
//WebDriver driver = new ChromeDriver();
//driver.navigate().to("https://google.co.in");
driver.navigate().to("https://testnwadmin.aditi.com/nwadmin/spages/home.aspx");
List<WebElement> ele = driver.findElements(By.xpath("//*[#id='divLoginSection']/div/div[3]"));
driver.findElement(By.id("Login1_txtEmailID")).sendKeys("testdata5#aditi.com");
//driver.findElement(By.id("Login1_txtPassword")).sendKeys("Testing1*");
driver.findElement(By.id("Login1_btnLogin")).click();
driver.findElement(By.xpath("//*[#id='sliding-navigation']/li[2]/a")).click();
String ViewMorelink="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[3]/td";
String ClkViewMore="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[3]//a[contains(text(),'View')]";
String Covered="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr[%s]/td[2]";
String ViewDetails="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr[%s]/td[3]/a";
String TableRowCount="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr";
String ViewCarrier="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr[%s]/td[3]";
String ClaimPayer="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr[%s]/td[4]";
Select WebList=new Select(driver.findElement(By.xpath("//*[#id='ddlSelectUser']")));
List<WebElement> userlist = WebList.getOptions();
int usercnt=userlist.size();
System.out.println(usercnt);
String[] linkTexts = new String[usercnt];
int i = 0;
for (WebElement e : userlist)
{
linkTexts[i] = e.getText();
i++;
}
for(int usrcnt=0;usrcnt<=usercnt;usrcnt++)
{
WebList.selectByIndex(usrcnt);
> /
> somecode
> /
}
}
}

Categories