How to control the browser that has been opened by nodejs - javascript

I want to know how to control the browser that has been opened? I’ve read the API docs, but I can't find the way to do it.
like java
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
WebDriver driver = new ChromeDriver(options);
or python
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
But how to do this by nodejs (javascript) ???
I’m so confused

Taken from https://medium.com/dailyjs/how-to-setup-selenium-on-node-environment-ee33023da72d
The script below will open a chrome browser, input a term, submit the
form, and return the page title. If the test is successful, then it
should print out Test passed
const webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
const driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
driver.get('http://www.google.com').then(function(){
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver\n').then(function(){
driver.getTitle().then(function(title) {
console.log(title)
if(title === 'webdriver - Google Search') {
console.log('Test passed');
} else {
console.log('Test failed');
}
driver.quit();
});
});
});

The below step will help you :
require('chromedriver');
var webdriver = require('selenium-webdriver');
var chrome = require("selenium-webdriver/chrome");
var chrome = require("selenium-webdriver/chrome");
var options = new chrome.Options();
options.options_["debuggerAddress"] = "127.0.0.1:9222";
var driver = new webdriver.Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build();
driver.get("https://www.google.com")

Related

ask for user input for selenium

I'm trying to automate my workflow using selenium in nodejs. When accessing sellercentral.amazon.com it sends an OTP code to my phone. How can I ask for a prompt at nodejs so I can input the code?
I've tried using readline-sync, but the prompt is always displayed even before selenium starts.
const webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
const driver = new webdriver.Builder()
.forBrowser('firefox')
// .setFirefoxOptions(options)
.build();
//Main body
driver.get('https://sellercentral.amazon.com');
driver.wait(until.elementLocated(By.id('sign-in-button')));
driver.findElement(By.id('sign-in-button')).click();
const fillForm = (idToLook, keys) => {
this.idToLook = idToLook;
if (keys) {
driver.wait(until.elementLocated(By.id(idToLook)));
driver.findElement(By.id(idToLook)).sendKeys(keys);
}
else {
keys = readline.question(`what are the keys for ${this.idToLook}: `);
driver.findElement(By.id(idToLook)).sendKeys(keys);
}
}
fillForm('ap_email', amazon.id);
fillForm('ap_password', amazon.password);
driver.findElement(By.name('rememberMe')).click();
driver.findElement(By.id('a-autoid-0')).click();
driver.wait(until.elementIsNotVisible(By.id('auth-mfa-optcode')));
// fillForm('auth-mfa-otpcode');
driver.findElement(By.id('auth-mfa-remember-device')).click();
driver.quit();
You may try something in similar fashion . Wrap initializeSite to launch the site as a Promise .
A base script like the below:
function main() {
var initializeSite = initialize();
initializeSite.then(function(result) {
// Do your different actions to bring up the form that need OTP
readline.question (“Add OTP”, (otp) =>{
// Add rest of your codes here
}
console.log(“success”)
}, function(err) {
console.log(err);
})
}

C# Selenium Headless Chrome Driver is not executing javascript from the website

I'm trying to scrape javascript generated html objects from a website. I've tried many different libraries and I found out that selenium has everything i need.
I've tried to run the driver without being in headless mode, and it WORKS,
but that's not what I need. I need a background task to keep the user interface as clean as possible.
var chromeOptions = new ChromeOptions();
chromeOptions.AddArgument("--no-startup-window");
chromeOptions.AddArgument("--user-agent=" + Settings.globalUserAgent);
chromeOptions.AddArgument("--log-level=3");
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
service.SuppressInitialDiagnosticInformation = true;
using(var driver = new ChromeDriver(service, chromeOptions))
{
driver.Url = "https://example.com";
driver.Navigate().GoToUrl("https://example.com/otherpage");
var wait = new WebDriverWait(driver, new TimeSpan(0, 0, 30));
var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("sub-conv-fu")));
string source = driver.PageSource;
if (source.Contains("some string:"))
{
File.WriteAllText("test.txt", source);
} else
{
File.WriteAllText("test.txt", source);
return "Error";
}
}
return "";
This line of code contains a variable which I want to get. It's loaded using javascript
var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("sub-conv-fu")));
It is working if I remove the "--headless" tag.

Unable to retrieve contents of Chrome Console using Selenium Webdriver in Node.js

I am trying to read the Chrome console using Selenium Webdriver in node.js, but so far it is unsuccessful. There are no errors. But all it returns is an empty array [].
The following is a snippet of the HTML and JavaScript function. When run manually in Chrome, these write to the console just fine.
<button name="button1" type="button" onclick="test_console()">Test</button>
function test_console() {
console.log("Hello World");
}
The following is the code I am using in node.js to try to get the output to Chrome.
const webdriver = require('selenium-webdriver');
const chromeDriver = require('selenium-webdriver/chrome');
const logging = require('selenium-webdriver').logging;
const path = require('chromeDriver').path;
const service = new chromeDriver.ServiceBuilder(path).build();
chromeDriver.setDefaultService(service);
const {By, Key} = webdriver;
webdriver.promise.USE_PROMISE_MANAGER = false;
const CHROME_BIN_PATH = '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome';
const prefs = new logging.Preferences();
prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL);
const options = new chromeDriver.Options();
options.setChromeBinaryPath(CHROME_BIN_PATH);
options.addArguments(
'headless',
'disable-gpu',
'verbose',
'disable-impl-side-painting',
);
const main = async () => {
try {
const driver = await new webdriver.Builder()
.withCapabilities(webdriver.Capabilities.chrome())
.setLoggingPrefs(prefs)
.forBrowser('chrome')
.setChromeOptions(options)
.build();
await driver.get('http://example.com/example.html');
//clicking this button manually in Chrome writes to the console
await driver.findElement(By.name('button1')).click();
await driver.manage().logs().get(logging.Type.BROWSER)
.then(function(entries) {
console.log(entries);
});
await driver.close();
await driver.quit();
} catch (error) {
await driver.close();
await driver.quit();
console.log(error);
}
};
main();
I'm sure the issue is simple, probably a configuration problem. I just cant figure out what the problem might be. I even resorted to reading the webdriver source code in Git to see if I could see anything, but to no avail.
As far as I can tell, getting the contents of the console from Chrome using webdriver is a no go.
I ended up solving the issue in this manner:
//append a div to the body of the page
await driver.executeScript("var div = document.createElement('div'); div.id = 'console_log'; document.body.appendChild(div);");
//override console.log to write the log message to the new div
await driver.executeScript("console.log = function(message){document.getElementById('console_log').innerHTML += message}");
//get the contents of the new div
const console_log = await driver.findElement(By.id('console_log'));
console.log(await console_log.getAttribute('innerHTML'));

WebDriver NodeJS Instantiate IE Driver with Capabilities: introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings)

I am trying to instantiate a driver session using the IE capabilities to ignore the protected mode settings in Internet Explorer, but I am unsure of the syntax.
I have tried:
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.ie().introduceFlakinessByIgnoringProtectedModeSettings(true).build();
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.ie().introduceFlakinessByIgnoringProtectedModeSettings, true.build();
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.ie().ignoreProtectedModeSettings(true).build();
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.ie().introduceFlakinessByIgnoringProtectedModeSettings(true).build();
var driver = new webdriver.Builder().withCapabilities({ "browserName": "ie" }, {"ignoreProtectedModeSettings": "true"}).build();
var driver = new webdriver.Builder().withCapabilities({ "browserName": "ie" }, {"introduceFlakinessByIgnoringProtectedModeSettings": "true"}).build();
Thus far none have worked. What is the correct sytax for this in Javascript? Thanks!!!
After having the same problem and going through the code for selenium-webdriver, I found the following to work:
const Capabilities = require('selenium-webdriver/lib/capabilities').Capabilities;
let capabilities = Capabilities.ie();
capabilities.set('ignoreProtectedModeSettings', true);
const driver = new webdriver.Builder().withCapabilities(capabilities).build();

assertion selenium webdriver node js

I am trying to run assertion for testing with selenium webdriver through node js but it says undefined, I get the page title which is URL of the page then assert it, looks like I have to import sth for assertion, please help, also please tell me if selenium works fine with node js here is my code:
var webdriver = require('selenium-webdriver'),
//var test = require('selenium-webdriver/testing'),
nodeThen = require('node-then');
var assert = require('assert');
//var jsdom = require("jsdom");
//var document = require('jquery');
var xpath = require('xpath');
//var driver = new webdriver.Builder().
// withCapabilities(webdriver.Capabilities.chrome()).
//build();
function createDriver() {
var driver = new webdriver.Builder()
.usingServer('link')
.withCapabilities(webdriver.Capabilities.chrome())
.build();
driver.manage().timeouts().setScriptTimeout(10000);
return driver;
}
var driver = createDriver();
var By = webdriver.By;
driver.get("URL")
.then(function(){
driver.sleep(10000);
var element=driver.findElement(By.id("get-started"));
element.click();
})
.then(function(){`enter code here`
return driver.getTitle();
})
.then(function(title) {
//console.log(title);
//driver.manage().timeouts().setScriptTimeout(50000);
if (title == ('URL')) {
console.log("pass");
}
//
I was searching for the same issue and I found this snippet which is working for me
driver.findElement(By.id('elementId'))
.getText().then(textValue => {
assert.equal('tested string', textValue);
});
I found it in the examples files of selenium-webdriver's github repo
Did you install asserts? The command would be npm install asserts. Also, you need var Asserts = require('asserts');
This is the example you are looking for
// Require chai.js expect module for assertions
const chai = require('chai');
const expect = require('chai').expect;
// Application Server
const serverUri = '0.0.0.0:3000';
// Official selenium webdriver testing setup
const webdriver = require('selenium-webdriver');
describe('basic test', function () {
let driver;
before(() => {
// Start of test use this
driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
console.log("Selenium Webdriver Chrome Started");
});
after(function(){
// End of test use this.
driver.quit();
});
it('should be on correct page', function (done) {
this.timeout(10000);
driver.get(serverUri);
driver.getTitle().then(function(title) {
expect(title).to.equal('Some String Here');
done();
console.log("Selenium Webdriver Chrome Shutdown");
})
});
});

Categories