Cannot get Java Selenium in headless mode - java

I've searched around for awhile now and it seems like i just need to add chrome options to get selenium to go into headless mode. I am quite new and i maybe missing something but i've tried the adding the code below into my scripts in to various areas and it doesn't seem to work.
ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=1400,800");
options.addArguments("headless");
I've tried the following
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeOptions;
public class TestPlan {
private static final WebDriver driver = new ChromeDriver();
#BeforeSuite
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", Utils.CHROME_DRIVER_LOCATION);
ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=1400,800");
options.addArguments("headless");
WebDriver driver = new ChromeDriver(options);
WebDriverWait wait = new WebDriverWait(driver, 30);
}
#Test(testName = "Login Page")
public static void wikiLogin() {
driver.get(Utils.WIKI_LOGIN_URL);
WikiLogin wikilogin = new WikiLogin(driver);
wikilogin.loginButton();
}
and
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeOptions;
public class TestPlan {
private static final WebDriver driver = new ChromeDriver();
#BeforeSuite
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", Utils.CHROME_DRIVER_LOCATION);
WebDriverWait wait = new WebDriverWait(driver, 30);
}
#Test(testName = "Login Page")
public static void wikiLogin() {
ChromeOptions options = new ChromeOptions();
options.addArguments("window-size=1400,800");
options.addArguments("headless");
WebDriver driver = new ChromeDriver(options);
driver.get(Utils.WIKI_LOGIN_URL);
WikiLogin wikilogin = new WikiLogin(driver);
wikilogin.loginButton();
}
With no success. Would appreciate some help. Thanks!

Related

The import org.openqa.selenium.chrome cannot be resolved

On Eclipse, The error red line was showing below the ChromeDriver statement and Line 18 (WebDriver driver = new ChromeDriver). Is that code correct?
Code:
package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
//import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class FirstTestNGFile {
public String baseUrl = "http://demo.guru99.com/test/newtours/";
String driverPath=
"C:\\Users\\manoj\\Documents\\QA\\COURSE\\ChromeDriver94\\chromedriver.exe";
//public WebDriver driver;
#Test
public void f() {
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", driverPath);
WebDriver driver = new ChromeDriver();
driver.get(baseUrl);
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
driver.close();
}
}
Yes it looks fine to me.
Additionally, you'd have to import WebDriver as well.
import org.openqa.selenium.WebDriver;
If that still did not work, I would suggest to take WebDriver driver out of #Test
Sample code :
private WebDriver driver;
public String baseUrl = "http://demo.guru99.com/test/newtours/";
String driverPath = "C:\\Users\\manoj\\Documents\\QA\\COURSE\\ChromeDriver94\\chromedriver.exe";
#Test
public void f() {
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.get(baseUrl);
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
driver.close();
}
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
// Few important imports in selenium to look.
// WebDriver interface is important for using methods
get(),getCurrentUrl(),findElement(),close(),quit() etc

How disable debuger on chrome webdriver in Java?

My target application use <script type="text/javascript">debugger;</script> So my page is blocked by break point.
How disable debugger on chrome webdriver in Java?
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import com.github.noraui.utils.Utilities.OperatingSystem;
import com.github.noraui.utils.Utilities.SystemArchitecture;
public class Bot {
public static void main(String[] args) {
final OperatingSystem currentOperatingSystem = OperatingSystem.getCurrentOperatingSystem();
String pathWebdriver = String.format("src/test/resources/drivers/%s/googlechrome/%s/chromedriver%s", currentOperatingSystem.getOperatingSystemDir(),
SystemArchitecture.getCurrentSystemArchitecture().getSystemArchitectureName(), currentOperatingSystem.getSuffixBinary());
System.setProperty("webdriver.chrome.driver", pathWebdriver);
ChromeOptions options = new ChromeOptions();
WebDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://rd.huangpuqu.sh.cn/website/html/shprd/shprd_tpxw/List/list_0.htm");
}
}
I think, add javascipt code (revert of debugger;) by this:
((JavascriptExecutor) driver).executeScript("...");
EDIT WITH HEADLESS MODE + SCREENSHOT:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import com.github.noraui.utils.Utilities.OperatingSystem;
import com.github.noraui.utils.Utilities.SystemArchitecture;
public class Bot {
public static void main(String[] args) throws IOException {
final OperatingSystem currentOperatingSystem = OperatingSystem.getCurrentOperatingSystem();
String pathWebdriver = String.format("src/test/resources/drivers/%s/googlechrome/%s/chromedriver%s", currentOperatingSystem.getOperatingSystemDir(),
SystemArchitecture.getCurrentSystemArchitecture().getSystemArchitectureName(), currentOperatingSystem.getSuffixBinary());
System.setProperty("webdriver.chrome.driver", pathWebdriver);
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);
driver.get("http://rd.huangpuqu.sh.cn/website/html/shprd/shprd_tpxw/List/list_0.htm");
final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
FileUtils.forceMkdir(new File(System.getProperty("user.dir") + File.separator + "downloadFiles"));
FileUtils.writeByteArrayToFile(new File(System.getProperty("user.dir") + File.separator + "downloadFiles" + File.separator + "bot.jpg"), screenshot);
}
}
The result is same, my sceenshot is white.

How can I use #BeforeTest for Capabilities class / or correctly extends on each #Test

I would like to create one class in which to insert #BeforeTest Capabilities. Referencing the below code, it is easy to insert tests into #Test.
Without TestNG everything works, but it doesn't work with TestNG.
Maybe I misunderstood something?
Class with Capabilities
public class test {
public static AndroidDriver<AndroidElement> Capabilities() throws MalformedURLException {
File f =new File("src");
File fs = new File(f,"ApiDemos-debug.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "demo");
capabilities.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath());
AndroidDriver<AndroidElement> driver= new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"),capabilities);
return driver;
}
Test example with extends Capabilities From test
public class swiping extends test {
public static void main(String[] args) throws MalformedURLException, InterruptedException {
AndroidDriver<AndroidElement> driver=Capabilities();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.findElementByXPath("//android.widget.TextView[#text='Views']").click();
driver.findElementByXPath("//android.widget.TextView[#text='Date Widgets']").click();
driver.findElementByAndroidUIAutomator("text(\"2. Inline\")").click();
driver.findElementByXPath("//*[#content-desc='9']").click();
Thread.sleep(1000);
TouchAction t=new TouchAction(driver);
WebElement first=driver.findElementByXPath("//*[#content-desc='15']");
WebElement second=driver.findElementByXPath("//*[#content-desc='45']");
t.longPress(longPressOptions().withElement(element(first)).withDuration(ofSeconds(2))).moveTo(element(second)).release().perform();
}
}
The below example shows a TestNG example of how to do the same thing.
The example leverages ThreadLocal so that tomorrow if you decide to run multiple #Test methods in parallel wherein every #Test method needs its own AndroidDriver instance, this would still work.
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import static io.appium.java_client.touch.offset.ElementOption.element;
import static java.time.Duration.ofSeconds;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestClassExample {
//We use thread local so that even if you decide to run tests in parallel, every #Test method
//will get its own AndroidDriver instance
private static final ThreadLocal<AndroidDriver> drivers = new ThreadLocal<>();
#BeforeMethod
public void setupDriver() throws MalformedURLException {
File f = new File("src");
File fs = new File(f, "ApiDemos-debug.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "demo");
capabilities.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath());
AndroidDriver driver =
new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
drivers.set(driver);
}
#AfterMethod
public void cleanupDriver() {
drivers.get().quit();
drivers.remove();
}
#Test
public void testMethod() throws InterruptedException {
AndroidDriver driver = drivers.get();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElementByXPath("//android.widget.TextView[#text='Views']").click();
driver.findElementByXPath("//android.widget.TextView[#text='Date Widgets']").click();
driver.findElementByAndroidUIAutomator("text(\"2. Inline\")").click();
driver.findElementByXPath("//*[#content-desc='9']").click();
Thread.sleep(1000);
TouchAction t = new TouchAction(driver);
WebElement first = driver.findElementByXPath("//*[#content-desc='15']");
WebElement second = driver.findElementByXPath("//*[#content-desc='45']");
t.longPress(longPressOptions().withElement(element(first)).withDuration(ofSeconds(2)))
.moveTo(element(second))
.release()
.perform();
}
}
PS: You should not be using #BeforeTest because that gets executed only once per <test> tag. You are better off using either a #BeforeClass (which gets executed once per test class (or) a #BeforeMethod (which gets executed once per #Test method)

Selenium Webdriver - Java, Browser shows message "ERROR: This page has expired. Please cancel this operation and try again" on button click

When I run the test method runSuite(), everything is fine till the last line of the method:
button.click(); // clicks the button on page
The above statement results in the page expired issue.
I get the following message on the browser window:
ERROR: This page has expired. Please cancel this operation and try again.
I tried playing around browser cache, but that didn't help.
package com.swtestacademy.webdriver;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Timeouts;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.*;
import com.util.MockLoginClient;
import static org.junit.Assert.*;
public class MainTest {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
MockLoginClient.instance().authenticateAsHcrCaseWorker();
//System.setProperty("webdriver.ie.driver","C:/IEDriverServer_x64_3.4.0/IEDriverServer.exe");
//driver = new InternetExplorerDriver();
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
options.addPreference("log", "{level: trace}");
capabilities.setCapability("marionette", true);
capabilities.setCapability("moz:firefoxOptions", options);
capabilities.setCapability(CapabilityType.ELEMENT_SCROLL_BEHAVIOR, 1);
capabilities.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, "applicationCacheEnabled");
System.setProperty("webdriver.gecko.driver", "C:/geckodriver-v0.16.1-win64/geckodriver.exe");
//ProfilesIni profile = new ProfilesIni();
//profile.getProfile("default");
FirefoxProfile ffprofile = new FirefoxProfile();
ffprofile.setPreference("browser.cache.disk.enable", true);
ffprofile.setPreference("browser.cache.memory.enable", true);
ffprofile.setPreference("browser.cache.offline.enable", true);
ffprofile.setPreference("network.http.use-cache", true);
driver = new FirefoxDriver(capabilities);//ffprofile);
//driver.manage().deleteAllCookies();
baseUrl = "http://localhost:8082/";
driver.manage().timeouts().implicitlyWait(3000, TimeUnit.MILLISECONDS);
//driver.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);
// driver.manage().timeouts().setScriptTimeout(3000,TimeUnit.MILLISECONDS);
driver.get(baseUrl + "/Curam/AppController.do");
}
#Test
public void test() throws Exception {
driver.get(baseUrl + "/Curam/AppController.do");
driver.findElement(By.id("app-sections-container-dc_tablist_DefaultAppSection-sbc_tabLabel")).click();
driver.findElement(By.cssSelector("div.dojoxExpandoIcon.dojoxExpandoIconLeft")).click();
Thread.sleep(1000);
driver.findElement(By.id("dijit_layout_AccordionPane_1_button_title")).click();
driver.findElement(By.cssSelector("#dijit_layout_AccordionPane_1 > ul > li > a.curam-content-pane-single-link")).click();
driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
iterator.next();
}
//driver.switchTo().window(subWindowHandler); // switch to popup window
driver.findElement(By.id("curam_ModalDialog_0"));
driver.findElement(By.className("dijitDialogPaneContent"));
driver.findElement(By.id("curam_ModalUIMController_0"));
driver.findElement(By.className("contentPanelFrameWrapper"));
driver.switchTo().frame("iframe-curam_ModalDialog_0");
driver.findElement(By.tagName("html"));
driver.findElement(By.tagName("body"));
driver.findElement(By.id("content"));
driver.findElement(By.id("mainForm"));
driver.findElement(By.id("modal-actions-panel"));
// driver.findElement(By.xpath("//div[#id='modal-actions-panel']/div[2]/a/span/span/span")).click();
WebElement nxtBtn = driver.findElement(By.id("__o3btn.NEXTPAGE_2"));
Thread.sleep(1000);
nxtBtn.click();
driver.findElement(By.xpath("//div[#id='modal-actions-panel']/div[2]/a[2]/span/span/span")).click();
driver.findElement(By.id("__o3btn.SAVE_0")).click();
}
#After
public void tearDown() throws Exception {
//driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
#Test
public void runSuite() throws InterruptedException {
System.out.println(driver);
WebElement xy = driver.findElement(By.id("app-sections-container-dc_tablist_DefaultAppSection-sbc_tabLabel"));
xy.click();
driver.findElement(By.cssSelector("div.dojoxExpandoIcon.dojoxExpandoIconLeft")).click();
WebElement personSearchLink = driver.findElement(By.linkText("Person…"));
Thread.sleep(1000);
personSearchLink.click();
WebElement appStc = driver.findElement(By.id("DefaultAppSection-stc"));
WebElement djtTab = appStc.findElement(By.className("dijitTabPaneWrapper"));
Thread.sleep(1000);
WebElement tpChldWrapper = djtTab.findElement(By.className("dijitTabContainerTopChildWrapper"));
WebElement lyoutCntntPane = tpChldWrapper.findElement(By.id("dojox_layout_ContentPane_1"));
WebElement tbWrpr = lyoutCntntPane.findElement(By.className("tab-wrapper"));
WebElement noDtlsPnl = tbWrpr.findElement(By.className("no-details-panel"));
WebElement cntntAreaCntnr = noDtlsPnl.findElement(By.className("content-area-container"));
WebElement fstUIMCntrlr = cntntAreaCntnr.findElement(By.id("curam_FastUIMController_1"));
WebElement cntntPnlFrmWrpr = fstUIMCntrlr.findElement(By.className("contentPanelFrameWrapper"));
WebElement iFrameElmnt = cntntPnlFrmWrpr.findElement(By.tagName("iframe"));
driver.switchTo().frame(iFrameElmnt);
WebElement inputText = driver.findElement(By.id("__o3id0"));
Thread.sleep(100);
inputText.sendKeys("24684");
// Thread.sleep(4000);
WebElement button = driver.findElement(By.linkText("Search"));
button.click();
}
}
I could see the issue. This behavior is seen for Firefox and Internet explorer only and not for chrome.
The solution would be to check the default desired capabilities for Chrome driver and set the same for Firefox driver or IE driver.
Easier Solution: Switch to Chrome Driver.

Selenium - org.openqa.selenium.chrome.ChromeDriver cannot be cast to com.thoughtworks.selenium.Selenium

I'm using flex-ui-selenium to automate my flex application, which adds 2 numbers and displays the result in an alert box.
Below is my selenium code:
package com.selenium.testcases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.thoughtworks.selenium.FlexUISelenium;
import com.thoughtworks.selenium.Selenium;
public class FlashSeleniumtest {
#SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\dev\\HydFramework\\Hyd\\HybridFrameWork\\jarsForAnt\\chromedriver.exe");
String BASE_URL = "C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\webapps\\FlexDemo\\SeleniumTest-debug\\SeleniumTest.html";
WebDriver driver = new ChromeDriver();
//FlashObjectWebDriver driver1 = new FlashObjectWebDriver((FlashObjectWebDriver) driver,"SeleniumTest");
driver.get(BASE_URL);
driver.manage().window().maximize();
FlexUISelenium flexUITester;
flexUITester = new FlexUISelenium((Selenium) driver, "SeleniumTest");
flexUITester.type("100").at("first");
flexUITester.type("200").at("second");
flexUITester.click("Sum");
}
}
When I execute this code, I get the following exception:
"org.openqa.selenium.chrome.ChromeDriver cannot be cast to com.thoughtworks.selenium.Selenium".
Please help.

Categories