How to use selenium + phantomJs in spring boot? - java

I want to use selenium + phantomJs in my Spring boot project for scrapy. I can make it work in a normal java app like this :
System.setProperty("phantomjs.binary.path", path_to_phantomjs.exe);
PhantomJSDriver driver = new PhantomJSDriver();
driver.get(a_web_url);
WebElement e = driver.findElementByXPath("//button[#title='load-more']");
e.click();
JSWaiter.setDriver(driver);
JSWaiter.waitJsJQueryAngular();
String html = driver.getPageSource();
System.out.println(html);
driver.quit();
I set phantomJs in my spring boot project like this
main
|__java
|__resources
|__static
|__phantomJs
|__pahntomjs.exe
Whether I call :
public static void main(String[] args)
{
System.setProperty("phantomjs.binary.path", "static/phantomJs/phantomjs.exe");
SpringApplication.run(PricecompareApplication.class, args);
}
or :
#RequestMapping(value = {"/crawl"}, method = RequestMethod.POST)
public String crawlProduct(Model model, CrawlerOption crawlOption)
{
System.setProperty("phantomjs.binary.path", "static/phantomJs/phantomjs.exe");
PhantomJSDriver driver = new PhantomJSDriver(); // <-- always error at this
}
My program alway throw this error when i create a new PhantomJSDriver :
java.lang.IllegalAccessError: tried to access class org.openqa.selenium.os.ExecutableFinder from class org.openqa.selenium.phantomjs.PhantomJSDriverService
It seem like I set the wrong path or I can not access the resources, but when I use the path to phantomjs.exe in my console app (the first code block in my question), still the same error .
How can I config selenium + phantomjs in Spring boot?

Related

Having trouble with SkipException, testNG, what am I doing wrong?

I am very new to selenium UI automation and I am trying my hands on with a simple application. I am using java with testNG. I need to integrate this test with CI and the test environment url will be different with every deployment. I am passing this as a parameter, difference between test and prod environment is that in the test, there won't be any login screen hence there is no need for authentication but my test verifies login and a login method. I need to be able to skip this test based on the URL supplied. Here is my code and the problem is testNG always suggests that the test was skipped but I can see it executing the login method. Please help me correct or understand what mistake I am committing.
public class Login {
WebDriver driver;
//Parameter - test environment URL
String url = System.getProperty("environment");
#Test (priority = 1)
public void verifyLogin() {
//Skip verifyLogin test in non prod environments
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
if (url=="www.google.com")
//If url matches production url then execute the test, if url doesn't match production URL then skip login test as there won't be any authentication/login in non prod
{
LoginPage login = new LoginPage(driver);
login.signIn();
Assert.assertEquals(driver.getTitle(), "Application Name", "Login failed,");
String title = driver.getTitle();
System.out.println("Page title is " + title);
driver.close();
}
else if (url!="www.google.com"){
throw new SkipException("Skipping this test");
}
}
#Test(priority = 2)
public void userKey() {
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
//If URL equals prod then call the login method to be able to login to the app else just execute the userKey method without having the need to login
if (url=="www.google.com");
{
LoginPage login = new LoginPage(driver);
login.signIn();
}
AccountManagementPage userKey = new AccountManagementPage(driver);
userKey.key();
driver.close();
}
}
The very exact use case is well explained here without throwing SkipException.
The idea is to create a custom annotation for the methods to be skipped & read the methods using IMethodInterceptor - decide to execute or not behind the scenes.
Updated for the question in the comment section:
You do not have to worry about 'TestEnvironment' or 'TestParameters' class.Just directly use the production check logic here.
Predicate<IMethodInstance> isTestExecutingOnProduction = (tip) -> {
return system.getProperty("env").
.equals("<production check here>");
};

The driver executable does not exist: D:\Firefox\geckodriver.exe

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class sasas {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","D:\\Firefox\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.manage().window().maximize();
driver.get(appUrl);
System.out.println("Test script executed successfully.");
driver.close();
}
}
this is the sample code i am trying. when i run i get the error message as "The driver executable does not exist: D:\Firefox\geckodriver.exe" please help me to proceed. i added the location in environmental variable then too i get this error . PATH i added as D:\Samplecode.
kindly help me
(1) To use gecko driver, make sure you are using Firefox version 55 and above to get better gecko Web-Driver feature support, find out more here
(2) Perhaps, you should downgrade Selenium to a lower version i.e. version 2.53.1. Selenium version 2.53.1 runs perfectly on Firefox 47.0.1 and lower, does not require using web driver API. I have ran your code against this and it worked fine.
public class Sasas {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.manage().window().maximize();
driver.get(appUrl);
System.out.println("Test script executed successfully.");
driver.close();
}
}
Use the relative path:
JAVA
1.- In your project, create the Drivers/Win/Firefox/geckodriver.exe folder and add your .exe
2.- Replace:
System.setProperty("webdriver.gecko.driver","D:\\Firefox\\geckodriver.exe");
For:
String path = System.getProperty("user.dir") + "/Drivers/Win/Firefox/Geckodriver.exe";
System.setProperty("webdriver.gecko.driver", path);
Note: using the relative path is the most optimal

Selenium don't recognize driver with jenkins

When I execute the jenkins job, the selenium test always fail with this error
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property
or when I set the driver path
not found /var/jenkins/.../C:/selenium/drivers/chromedrive
I have the follow environment
1 jenkins server and selenium hub running on linux
1 selenium node running on Windows.
The selenium node is running with the follow line
java -Dwebdriver.chrome.driver=C:/selenium/drivers/chromedriver.exe -jar selenium-server-standalone-2.53.1.jar -port 5556 -role node -hub http://192.168.15.99:4444/grid/register -browser "browserName=chrome, version=ANY, maxInstances=10, platform=WINDOWS"
Selenium hub and node can see each other.
Why I can't execute the tests? Look's like selenium are trying to execute on the hub, not on the node. How can I configure to do not ask for Chrome driver location?
My test
public class TesteSelenium{
private static final String APLICATION_CONTEXT = "/SYSA";
WebDriver driver;
HomePage home;
#Before
public void setUp() {
Properties p = PropertiesUtil.getProperties();
File file = new File(p.getProperty("webdriver.path"));
System.setProperty(p.getProperty("webdriver.type"), file.getAbsolutePath());
driver = new ChromeDriver();
driver.get(p.getProperty("host.address")+APLICATION_CONTEXT);
LoginPage login = PageFactory.initElements(driver, LoginPage.class);
login.setUsuarioTextField(p.getProperty("usuario.selenium.login"));
login.setSenhaPasswordField(p.getProperty("usuario.selenium.password"));
home = login.submit();
}
#After
public void finish() {
driver.close();
}
I use a properties file
host.address = http://jbossserver:8080
usuario.selenium.login = USER_SELENIUM
usuario.selenium.password = 123123
webdriver.path = C:/selenium/drivers/chromedriver
webdriver.type = webdriver.chrome.driver
You should have your parameters inside quotation marks in command line. Like this:
java -Dwebdriver.chrome.driver="C:/selenium/drivers/chromedriver.exe"
The code to run Selenium tests remotely is slightly different.
public void setUp() throws MalformedURLException {
Properties p = PropertiesUtil.getProperties();
//File file = new File(p.getProperty("webdriver.path"));
//System.setProperty(p.getProperty("webdriver.type"), file.getAbsolutePath());
DesiredCapabilities capability = DesiredCapabilities.chrome();
//driver = new ChromeDriver();
WebDriver driver = new RemoteWebDriver(new java.net.URL("http://seleniumHubIp:4444/wd/hub"), capability);
driver.get(p.getProperty("host.address")+APLICATION_CONTEXT);
LoginPage login = PageFactory.initElements(driver, LoginPage.class);
login.setUsuarioTextField(p.getProperty("usuario.selenium.login"));
login.setSenhaPasswordField(p.getProperty("usuario.selenium.password"));
home = login.submit();
}
My mistake was writing the code to run local tests on a remote selenium node.

How to find Frame element using PhantomJS?

I am working on frame based website. I am using selenium 2.47.1 & PhantomJS 1.9.2. I have written Automation Script & run it using firefox driver, it works perfectly. I am trying to execute the code with help PhanthomJS driver. But whenever I am trying to execute the it gives NoSuchFrameFoundException. My script is given below...
public class iFrame {
public String baseUrl = "https://test5.icoreemr.com/interface/login/login.php";
public WebDriver cd;
String scenarioName = "Sheet1";
ExcelLibrary ex = new ExcelLibrary();
#BeforeTest
public void SetBaseUrl() {
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability(
PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
"C:\\Users\\Probe7\\Downloads\\phantomjs-1.9.2-windows\\phantomjs.exe"
);
this.cd = new PhantomJSDriver(caps);
cd.get(baseUrl);
cd.manage().window().maximize();
}
#Test(priority = 0)
/* Login into the Application */
public void Login() {
cd.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
cd.switchTo().frame("Login");
System.out.println("Control Moved to Login Frame");
String UserName = ex.getExcelValue(scenarioName, 2, 4);
cd.findElement(By.xpath("//body/center/form/table/tbody/tr/td/div/div[2]/table/tbody/tr[1]/td[2]/input")).sendKeys(UserName);
}
Above code gives following exception..
org.openqa.selenium.NoSuchFrameException: No frame element found by name or id Login
Eventhough same script works perfectly in firefox driver, but not in PhantomJS.
Please advice me what went wrong?? I am looking into this nearly a day, but didn't find any solution.. Please help me on this?
Thanks in Advance...

Accessing web pages automatically using selenium

I'm trying to access a webpage using Selenium.
I use the WebDriver and HtmlUnitDriver classes:
WebDriver driver = new HtmlUnitDriver();
WebElement element;
Then to get a webpage I use:
driver.get("url");
url being the specific url of a page.
However, this does not work for all pages? When accessing some pages the program just halts and nothing happens. What I'm doing is logging into a web page, buying some stuff, and all that works, but when I want to go to the check-out and finish the order the check-out page does not load.
you can use some functions like these
public String openBrowser(String object, String data,String configPath) {
APP_LOGS.debug("Opening browser");
if (CONFIG.getProperty(data).equals("Mozilla"))
driver =new FirefoxDriver();
else if (CONFIG.getProperty(data).equals("IE"))
driver =new InternetExplorerDriver();
else if (CONFIG.getProperty(data).equals("Chrome"))
driver =new ChromeDriver();
else if (CONFIG.getProperty(data).equals("Safari"))
driver =new SafariDriver();
driver.manage().window().maximize() ;
}
public String clickButton(String object, String data,String configPath){
OR=new ObjectRepLocator(ObjectRepo);
APP_LOGS.debug("Clicking on Button");
try{
driver.findElement(By.xpath(OR.getLocator(object,configPath))).click();
}catch (Exception e){
return Constants.KEYWORD_FAIL+ " Not able to click on button"+e.getMessage();
}
return Constants.KEYWORD_PASS;
}
Better way is you can get those values for processing this from Excel sheets. I am using the data driven framework that proceeds in this way

Categories