Katalon keeps open browser when executed as headless - selenium

i have automation code in Katalon studio and i want to execute it in headless.
I've already add argument for headless in chromeoptions. I have also executed it in Chrome(headless) mode. But it still open browser and execute it like normal WebUI.
Below is my code :
class My_WebScraper {
ChromeOptions options = new ChromeOptions();
String ProjectDirectory=RunConfiguration.getProjectDir()
String downloadPath = ProjectDirectory+"/Screenshot"
Map<String, Object> chromePrefs = new HashMap<String, Object>()
DesiredCapabilities cap = DesiredCapabilities.chrome()
String popup_dialog = "//div[#role='dialog']"
String General_Button = "//button[text()='{PARAM}']"
String General_Tab_Menu = "//div[#class='gnb']/ul[#class='g_menu' and #id='top1menu']/li/a[text()='{PARAM}']"
String Left_Menu_of_Mainmenu_Pemantauan = "//div[#id='left_menu']/div[#class='clearfix']/aside[#class='sidebar']/nav[#class='sidebar_nav']/ul[#class='metismenu' and #id='menu']/li/ul[#id='left-menu' and #class='LeftMnRow']/li/a/span[text()='Pemantauan Aktivitas']"
String Pemantauan_Aktivitas_expanded = "//div[#id='left_menu']/div[#class='clearfix']/aside[#class='sidebar']/nav[#class='sidebar_nav']/ul[#class='metismenu' and #id='menu']/li/ul[#id='left-menu' and #class='LeftMnRow']/li/a/span[text()='Pemantauan Aktivitas']/../../ul[#aria-expanded='true' and #class='collapse in']/li/a[text()='{PARAM}']"
String FileLog
String filename
def replace(String x,oldc,newc){
String str = new String(x)
return str.replace(oldc, newc)
return str
}
#Given("Login")
def capture_captcha() throws IOException, InterruptedException{
println(downloadPath)
chromePrefs.put("download.default_directory", downloadPath)
options.setExperimentalOption("prefs", chromePrefs)
options.addArguments("--window-size=1920,1080");
options.addArguments("--disable-gpu");
options.addArguments("--disable-extensions");
options.addArguments("–no-sandbox");
options.addArguments("–disable-dev-shm-usage");
options.addArguments("--disable-software-rasterizer");
options.addArguments("--disable-blink-features='BlockCredentialedSubresources'")
options.addArguments("--no-proxy-server")
options.addArguments("--disable-web-security")
options.addArguments("--allow-running-insecure-content")
options.addArguments("--ignore-certificate-errors")
options.addArguments("–-headless");
cap.setCapability(ChromeOptions.CAPABILITY, options)
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true)
options.merge(cap);
System.setProperty("webdriver.chrome.driver", DriverFactory.getChromeDriverPath())
WebDriver driver = new ChromeDriver(options);
driver.get("https://myweb.com");
driver.manage().window().maximize();
WebUI.delay(3)
can anyone help me,please?
thank you

Your test script used the new driver instance, not the driver instance from WebUI keyword.
The solution here is to override the capabilities from which you can refer here

Related

When I execute selenium script, following it browser is being closed Automatically?

I am writing selenium script and It's working perfect but when code is running then my browser is automatically closed?
public static void main(String args[])
{
System.setProperty("webdriver.chrome.driver",
"./chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("URL");
String email = "EMAil";
String password = "123";
int ELEMENT_WAIT_TIME_SEC = 60;
WebDriverWait explicitWait = new WebDriverWait(driver, ELEMENT_WAIT_TIME_SEC);
String locator = "//input[#type='email'][#aria-label='Email']";
By findBy = By.xpath(locator);
WebElement Login = explicitWait.until(ExpectedConditions.elementToBeClickable(findBy));
Login.click();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].setAttribute('aria-invalid',true);", Login);
Login.sendKeys(email);
String plocator = "//input[#type='password'][#aria-label='Password']";
By findByp = By.xpath(plocator);
WebElement Password = explicitWait.until(ExpectedConditions.elementToBeClickable(findByp));
Password.click();
jse.executeScript("arguments[0].setAttribute('aria-invalid',true);", Password);
Password.sendKeys(password);
}
Check your code. May be you used driver.close() method to close the browser.
Just comment or delete that code and the browser will not close automatically.
I got over this error by using the Code Runner extension of VS Code instead of manually running node file-path.
Works well.
This is a case of browser version compatibility issue with chrome. so update your chromedriver.exe in sync with current version of Chrome browser.

How to add flags to webdrive using JS?

I want to add this attribute
chrome://flags/#mark-non-secure-as
Part of the webdriver
I saw that I can add with
var capabilities = webdriver.Capabilities.chrome();
Is it the right way ?
If yes which attribute do I need to add this attribute
https://sites.google.com/a/chromium.org/chromedriver/capabilities
The value that I want to pass is Always mark Http as neural , Does it have any constant ?
var TestConfiguration = require("./globalConfiguration"),
webdriver = require('selenium-webdriver'),
proxy = require('selenium-webdriver/proxy');
module.exports = {
createDriver: function () {
var capabilities = webdriver.Capabilities.chrome();
capabilities.chromeOptions = {
args: ['mark-non-secure-as=NEUTRAL']
};
var manualProxy = TestConfiguration.getParam(TestConfiguration.KEYS.PROXY);
var proxyToSet = proxy.system();
if (manualProxy) {
proxyToSet = proxy.manual({http: manualProxy, https: manualProxy});
}
var driver = new webdriver.Builder().withCapabilities(capabilities).
usingServer(TestConfiguration.getParam(TestConfiguration.KEYS.SELENIUM_HOST))
.setProxy(proxyToSet)
.build();
return driver;
}
};
You did not specify whether you are using C# or Java version of the selenium driver but the code is basically the same either way. The c# code below opens chrome with the attribute 'chrome://flags/#mark-non-secure-as' set.
You just need to create a ChromeOptions object set the desired options and pass it to the driver constructor.
https://sites.google.com/a/chromium.org/chromedriver/capabilities
ChromeOptions options = new ChromeOptions();
options.AddArgument("--mark-non-secure-as");
IWebDriver driver = new ChromeDriver(options);
I used version 3.3 of Webdriver.dll and the Chrome driver from: https://sites.google.com/a/chromium.org/chromedriver/getting-started

Setting separate profiles for Parallel Selenium Tests

I am researching how to set an individual profile using RemoteWebDriver. I have been reading about it on the following thread.
http://stackoverflow.com/questions/12961037/parallel-execution-of-firefoxdriver-tests-with-profile-share-same-profile-copy
I am trying to tackle it as following:
public static RemoteWebDriver getDriver(String methodName) throws MalformedURLException {
String SELENIUM_HUB_URL = "http://localhost:4444/wd/hub";
ThreadLocal<RemoteWebDriver> remoteWebDriver = null;
File currentProfileFile = new File(methodName);
//This is where it gives the error
FirefoxProfile currentFireFoxProfile = new FirefoxProfile(currentProfileFile);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(FirefoxDriver.PROFILE, currentFireFoxProfile);
String proxy = System.getProperty("proxy");
try {
remoteWebDriver = new ThreadLocal<RemoteWebDriver>();
remoteWebDriver.set(new RemoteWebDriver(new URL(SELENIUM_HUB_URL),
capabilities));
} catch (MalformedURLException e) {
System.out.println("Please fix the RemoteDriverSetup.class");
}
remoteWebDriver.get().manage().window()
.setSize(new Dimension(2880, 1524));
remoteWebDriver.get().manage().timeouts()
.pageLoadTimeout(10, TimeUnit.SECONDS);
remoteWebDriver.get().manage().timeouts()
.implicitlyWait(10, TimeUnit.SECONDS);
return remoteWebDriver.get(); // Will return a thread-safe instance of the WebDriver
}
I am getting the following error :
Time elapsed: 1.044 sec <<< FAILURE!
org.openqa.selenium.firefox.UnableToCreateProfileException: Given model profile directory does
not exist: TEST001
Update : I am injecting method name in the BaseTest class below
#BeforeMethod
public void startTest(Method testMethod) {
LOG.info("Starting test: " + testMethod.getName());
this.driver = WebDriverSetup.getDriver(testMethod.getName());
}
If you don't want to customize anything on your Firefox profile, better to create Firefox webdriver instance by NOT providing any profile details (as mentioned by Nguyen).
If you really want to create separate profiles (may be required to install some plug-ins like Firebug), in that case, you can do that by without passing any file name as below:
FirefoxProfile currentFireFoxProfile = new FirefoxProfile();
//Do some customization - add extension
currentFireFoxProfile.addExtension(pathOfextensionToInstall);
//or Setup some Firefox config. switch values
currentFireFoxProfile.setPreference("browser.download.manager.showWhenStarting", false);

How to configure and setup HTMLUNIT with Selenium while using it in C#?

I setup selenium remote driver and run the selenium server.The selenium server running correctly and while I try to run my code using :
var remoteServer = new Uri("http://127.0.0.1:4444/wd/hub");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.Firefox();
desiredCapabilities.IsJavaScriptEnabled = true;
myDriver = new RemoteWebDriver(remoteServer, desiredCapabilities, new TimeSpan(0,1, 30));
No error throws in the CMD log and elements can find properly, but headache comes while I try to run this using the below code :
var remoteServer = new Uri("http://127.0.0.1:4444/wd/hub");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.HtmlUnit();
desiredCapabilities.IsJavaScriptEnabled = true;
myDriver = new RemoteWebDriver(remoteServer, desiredCapabilities, new TimeSpan(0, 1, 30));
in log it throws lots of error and while I try to find any element, timeout exception showing in log.
My test code is in below :
myDriver.Manage().Window.Maximize();
myDriver.Navigate().GoToUrl(tollFreeURL);
IWebElement planClick = myDriver.FindElement(By.ClassName("trial"));
planClick.Click();
IWebElement startPlan = myDriver.FindElement(By.Id("choose2000"));
startPlan.Click();
IWebElement selectValue = myDriver.FindElement(By.Name("AreaCode"));
var selectElement = new SelectElement(selectValue);
selectElement.SelectByValue("800");
IWebElement selectNumber = myDriver.FindElement(By.XPath("//*[#id='divList']/div[1]"));
tollFreeNumber = selectNumber.Text;
tollFreeNumber = stringConvert.StringRefiner(tollFreeNumber, " ");
tollFreeNumber = stringConvert.StringRefiner(tollFreeNumber, "(");
tollFreeNumber = stringConvert.StringRefiner(tollFreeNumber, ")");
tollFreeNumber = stringConvert.StringRefiner(tollFreeNumber, "-");
Console.WriteLine(tollFreeNumber);
My target is to run the application in background and generate data, so I do not have any option to run this using Firefox.HTMLUNIT is the only option for me.Help needed it will stuck me last 3-4 days.
I believe your machine is using proxy servers. Try by adding that proxy configuration while creating driver instance.
String PROXY = "xx.xx.xx.xx:8080";
OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
Add proxy setting to desired Capabilities:
desiredCapabilities.SetCapability(CapabilityType.PROXY, proxy);

Facebook Logout Script

Can you please let me know how we can logout in chrome browser by using selenium?
e.g
public class AJ {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://facebook.com");
WebElement element=driver.findElement(By.name("email"));
element.sendKeys("user#example.com");
element=driver.findElement(By.name("pass"));
element.sendKeys("password");
element.submit();
The following code should help you.
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://facebook.com");
WebElement element=driver.findElement(By.name("email"));
element.sendKeys("user#example.com");
element=driver.findElement(By.name("pass"));
element.sendKeys("password");
element.submit();
//Click on dropdown menu then logout button
driver.findElement(By.id("userNavigationLabel")).click();
driver.findElement(By.id("logout_form")).click();
//Check to see if email login box is available
//therefore confirming user has logged out
driver.findElement(By.name("email"));
}
I recommend using the Chrome Developer tools to help you find unique attributes of a page for Selenium to find.
I hope this helps!
In python the same is done using this line of code. It uses the same module i.e, Selenium.
So just change the element using css selector by using the argument passed below.
logout1 = driver.find_element_by_css_selector("._w0d[action='https://www.facebook.com/logout.php?button_name=logout&button_location=settings']").submit()
Hope it works.
I am able to successfully logout from Facebook.
Here is the Java code
String url = "http://facebook.com";
String email = "email";
String password = "password";
System.setProperty("webdriver.chrome.driver", "src/chromedriver 3");
WebDriver driver = new ChromeDriver();
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
driver = new ChromeDriver(options);
driver.get(url);
driver.manage().window().maximize();
driver.findElement(By.id("email")).sendKeys("Your email here");
driver.findElement(By.id("pass")).sendKeys("Your password here" + Keys.ENTER);
driver.findElement(By.id("logoutMenu")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//form[contains(#id,'show_me_how_logout')]/../../../..")).click();