Setting service_args for phantomjs in selenium-webdriver for node - javascript

I need to be able to run phantomjs with the following arg:
--ignore-ssl-errors=true
The page I'm testing uses a self-signed cert so I need the arg to open the page. I'm trying to pass the arg in webdriver using the snippet below:
capabilities = webdriver.Capabilities.phantomjs();
capabilities.set('service_args', '--ignore-ssl-errors=true');
driver = new webdriver.Builder().
withCapabilities(capabilities).
build();
Is the correct way to pass the service_args? I actually hope not since I can't load my test page. I can open the page by running:
phantomjs --ignore-ssl-errors=true myTest.js
Here is the code in myTest.js
var page = new WebPage();
page.open('https://my.somefaketestpage.com/', function (status) {
just_wait();
});
function just_wait() {
setTimeout(function() {
page.render('screenshot.png');
phantom.exit();
}, 2000);
}

The correct answer is:
caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] {"--web-security=no", "--ignore-ssl-errors=yes"});
driver = new PhantomJSDriver(caps);
documented here: https://github.com/detro/ghostdriver/issues/233

In case someone will need it for facebook/php-webdriver CLI arguments can be passed to PhantomJS in a following manner:
$driver = RemoteWebDriver::create('http://localhost:4444/wd/hub', [
WebDriverCapabilityType::BROWSER_NAME => WebDriverBrowserType::PHANTOMJS,
WebDriverCapabilityType::PLATFORM => WebDriverPlatform::ANY,
'phantomjs.cli.args' => ['--ignore-ssl-errors=true']
]);

Reading this I got really confused, as the accepted answer is in Java, and the GhostDriver constants and stuff aren't present. For those who are also confused, this worked for me:
var webdriver = require('selenium-webdriver'),
Capabilities = webdriver.Capabilities;
var capability = Capabilities
.phantomjs()
.set('phantomjs.cli.args', '--ignore-ssl-errors=true');
var driver = new webdriver
.Builder()
.withCapabilities(capability)
.build();

Related

TypeError: Assignment to constant variable ,After Changing it to let/var

Im trying to set the binary path of a binary of chrome with selenium, in javascript language.
unfortunately, my knowledge in javascript is limited, and Im getting an error while trying to do so, in which I cannot solve, despite my efforts.
so without further ado, I will now share my problem, with the hope that someone with a better knowledge in javascript then me, will help me
some background:
Im triggering a function in the firebase could functions,
inside this function , I'm trying to create a selenium webdriver.
in order to do so:
I need to do those things:
chromedriver --> that work on a linux system(located inside the functions project folder)✅
chrome browser binary that is located on this machine ✅
3.then, I need to create a a chrome Options object.
a. adding an Argument so it will be headless.✅
b. setting it with a path to the chrome binary.❌
and at last, create a chrome driver with options, that I have created
currently, I'm at stage 3.b
the error that rise coming from my poor knowledge in javascript
this is the error :
TypeError: Assignment to constant variable.
here what's lead to this error
this is my code :
exports.initializedChromeDriver = functions.https.onRequest((request, response) => {
async function start_chrome_driver() {
try {
functions.logger.info('Hello logs!', {structuredData: true});
console.log("did enter the function")
const google_site = "https://www.gooogle.com";
const { WebDriver } = require('selenium-webdriver');
const {Builder, By} = require('selenium-webdriver');
console.log("will try to initialzed chrome");
let chrome = require('selenium-webdriver/chrome');
console.log("did initialzed chrome");
var chrome_options = new chrome.Options()
console.log("will try to set the chrome binary Path");
functions.logger.info('new chrome.Options()', {structuredData: true});
chrome_options = chrome_options.setChromeBinaryPath(path="/usr/bin/google-chrome");// <------- THIS IS THE LINE THAT RISE THE ERROR!
console.log("did setChromeBinaryPath");
chrome_options.addArguments("--headless");
let buillder = new Builder().forBrowser('chrome');
functions.logger.info(' did new Builder().forBrowser(chrome)', {structuredData: true});
const google_site = 'https://wwww.google.com'
await driver.get(google_site);
functions.logger.info('driver did open google site', {structuredData: true});
return "succ loading google"
}
catch (err) {
console.log('did catch')
console.error(err);
return "error loading google";
}
}
const p = start_chrome_driver().then((value,reject) => {
const dic = {};
dic['status'] = 200;
dic['data'] = {"message": value};
response.send(dic);
});
and here's the error that follows this code in the firebase functions logs:
I tried to change the chrome_options object into var/let, and looking for answers in the web , but after deploying again, and again, and again.. I feel like its time to get another perspective, any help will do.
You have an unnecessary assignment here (path=...)
chrome_options = chrome_options.setChromeBinaryPath(path="/usr/bin/google-chrome");
Just remove the assignment to path
chrome_options = chrome_options.setChromeBinaryPath("/usr/bin/google-chrome");

Selenium webdriver TypeError: element.isDisplayed is not a function

I have an error:
TypeError: element.isDisplayed is not a function
When executing the following code:
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var driver = new webdriver.Builder()
.forBrowser('chrome')
.usingServer('http://localhost:4444/wd/hub')
.build();
driver.get('https://www.test.com');
driver.wait(until.elementIsVisible(By.id('someButton')), 5000);
This is on my local machine using https://www.npmjs.com/package/selenium-webdriver and kicking off a server with:
webdriver-manager start
My spec:
Mac oSX Sierra 10.12.6
Chrome v60
The site I'm developing on is using AJAX to load pages to this could make a difference?
Problem
until.elementIsVisible(..) needs a WebElement an not a Locator as a Argument.
Solution
Writing
driver.wait(until.elementIsVisible(driver.findElement(By.id('someButton'))), 5000);
instead of
driver.wait(until.elementIsVisible(By.id('someButton')), 5000);
will solve the Problem.
More Infos
http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/until.html
https://github.com/SeleniumHQ/selenium/issues/2935

Htmlunit driver has trouble with Javascript

I wrote a Selenium test with java that I launched with the FirefoxDriver and it is executing fine in Firefox browser.
Then I am replacing FirefoxDriver with HtmlunitDriver like this:
driver = new FirefoxDriver();
with
driver = new HtmlUnitDriver(true);
But then I got this error :
It's missing ';' Before an instruction (http://local.project/bundles/app/js/socket.js#1)
This is the socket.js file :
class SocketHandler {
constructor(url) {
this.url = url;
this.session = null;
}
....
}
I suspect that it doesn't recognize the class declaration. Any idea how to correct that please?
You don't even need to use PhantomJs. As PhantomJs is not so much maintain these days. You can use chromedriver in headless mode.
you just need to add options as headless as below :-
chromeOptions.addArguments("--headless");
Please find complete code below:
System.setProperty("webdriver.chrome.driver","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\chromedriver.exe");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://google.com");
While if still you want to use phantomjs. then first download phantomjs binary from below location :-
http://phantomjs.org/download.html
Now use below code :-
System.setProperty("phantomjs.binary.path","D:\\Workspace\\JmeterWebdriverProject\\src\\lib\\phantomjs\\phantomjs.exe");
DesiredCapabilities capabilities = null;
ArrayList<String> cliArgsCap = new ArrayList<String>();
capabilities = DesiredCapabilities.phantomjs();
cliArgsCap.add("--web-security=false");
cliArgsCap.add("--ssl-protocol=any");
cliArgsCap.add("--ignore-ssl-errors=true");
capabilities.setCapability("takesScreenshot", true);
capabilities.setJavascriptEnabled(true);
capabilities.setCapability(
PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);
capabilities.setCapability(
PhantomJSDriverService.PHANTOMJS_GHOSTDRIVER_CLI_ARGS,new String[] { "--logLevel=2" });
driver = new PhantomJSDriver(capabilities);
driver.get("https://www.google.co.in/");
Hope it will help you :)

How to use PhantomJS for opening a sitelink using Selenium Webdriver?

I am trying to use headless Webkit of PhantomJS to open google.com through Selenium Webdriver but when I execute the following code system, some error occurs. Have I missed something?
var webdriver = require('selenium-webdriver');
var By = require('selenium-webdriver').By;
var driver = new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.phantomjs())
.build();
var baseUrl = 'http://google.com/';
driver.get(baseUrl);
driver.findElement(By.name('q')).sendKeys('webdriver');
driver.findElement(By.name('btnG')).click();
driver.wait(until.titleIs('webdriver - Google Search'), 1000);
driver.quit();
But I am getting a new error:
Require until first:
var until = require('selenium-webdriver').until;

Error using getWindowHandles in Selenium WebDriverJS

There is a question very similar to this asking how to do what I want to do, but the answer is not working for me. I do not have enough reputation to comment or ask for clarification on that yet.
I am using JavaScript and WebDriverJS with NodeJS
I am trying to switch to a new window that just opened up with a target=_blank link.
I seem to have boiled the problem down to driver.getWindowHandles() giving me an error.
Trimmed down Node js file:
var webdriver = require("selenium-webdriver");
var driver = new webdriver.Builder().usingServer().withCapabilities({'browserName': 'chrome' }).build();
driver.get('https://www.google.com');
driver.getTitle().then(function (title) {
console.log(title);
var handles = driver.getWindowHandles();
});
driver.getTitle().then(function (title) {
console.log(title);
});
This is what my command line looks like:
C:\selenium>node test2.js
Google
C:\selenium\node_modules\selenium-webdriver\lib\goog\async\nexttick.js:39
goog.global.setTimeout(function() { throw exception; }, 0);
^
TypeError: undefined is not a function
at C:\selenium\test2.js:8:23
at promise.ControlFlow.runInFrame_ (C:\selenium\node_modules\selenium-webdri
ver\lib\webdriver\promise.js:1877:20)
at promise.Callback_.goog.defineClass.notify (C:\selenium\node_modules\selen
ium-webdriver\lib\webdriver\promise.js:2464:25)
at promise.Promise.notify_ (C:\selenium\node_modules\selenium-webdriver\lib\
webdriver\promise.js:563:12)
at Array.forEach (native)
at Object.goog.array.forEach (C:\selenium\node_modules\selenium-webdriver\li
b\goog\array\array.js:203:43)
at promise.Promise.notifyAll_ (C:\selenium\node_modules\selenium-webdriver\l
ib\webdriver\promise.js:552:16)
at goog.async.run.processWorkQueue (C:\selenium\node_modules\selenium-webdri
ver\lib\goog\async\run.js:125:21)
at runMicrotasksCallback (node.js:337:7)
at process._tickCallback (node.js:355:11)
If I comment out the var handles... line then the script finishes with no error and prints the text "google" twice to the command prompt.
I figured it out!
1) The call is getAllWindowHandles in javascript. It drives me batty how each language api seems to have differently named methods for the same thing.
Reference for the webdriverJS webdriver class:
http://selenium.googlecode.com/git/docs/api/javascript/class_webdriver_WebDriver.html
2) The return is a promise, not the actual array I wanted, so it is easier to handle in a .then statement.
new code that prints out:
Google
[array of open window names]
Google
var webdriver = require("selenium-webdriver");
var driver = new webdriver.Builder().usingServer().withCapabilities({'browserName': 'chrome' }).build();
driver.get('https://www.google.com');
driver.getTitle().then(function (title) {
console.log(title);
driver.getAllWindowHandles().then(function (allhandles) {
console.log(allhandles);
});
});
driver.getTitle().then(function (title) {
console.log(title);
});

Categories