Take multiple browser snapshots - selenium

I am an ASP.NET web developer and need to submit artifacts of the developed page, to the testers.
These include:
Snapshots of the page when opened in different browsers.
Same thing, with different versions of the browsers.
I do this manually (one by one) and also from different systems.(because IE8 is available only at a particular system...so on..). Yes of course time consuming.
Is there a way that could simplify my life in this.(something like browserstack.com)
I am looking at Selenium grid. But this requires some coding too and using eclipse etc. Not sure yet if taking screenshots is possible too and I have no knowledge of selenium.
Appreciate any help in this. Thank you

Create a config file for the Selenium Hub
The file name should be for example hubConfig.json and save it in the same folder where you will start the Hub. The host contains the IP of the HUB and the port contains the port number ... :)
{
"host": "127.0.0.1",
"port": 4444
}
Run your Selenium Hub, and load the configuration file too
Create a new file with the following name: startSeleniumHub.cmd and add the following command in it:
java -jar selenium-server-standalone.jar -role hub -hubConfig hubconfig.json
You can download the latest version Selenium Server Standalone on the Selenium HQ website:
http://www.seleniumhq.org/download/
Create a config file for the Node
The file name should be for example nodeConfig.json and save it in the same folder on the same PC where you will start the Node.
{
"capabilities":[
{
"platform":"WINDOWS",
"browserName":"firefox",
"firefox_binary":"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
"maxInstances":5,
"seleniumProtocol":"WebDriver"
},
{
"platform":"WINDOWS",
"browserName":"chrome",
"maxInstances":5,
"seleniumProtocol":"WebDriver"
},
{
"platform":"WINDOWS",
"browserName":"internet explorer",
"maxInstances":5,
"version":11,
"seleniumProtocol":"WebDriver"
}
],
"configuration":{
"port":5555,
"host":"IP_OF_THE_NODE_PC",
"register":true,
"hubHost":"IP_OF_THE_HUB",
"hubPort": 4444,
"maxSession":1
}
}
If something is not understandable for you in this config, you can read more details about it on the following page:
https://code.google.com/p/selenium/wiki/Grid2
If you want, you can add more browsers like Edge, Safari, Opera, etc...
Connect your PCs to the Selenium Hub as a Node with the configuration file and with the WebDrivers as well
Create a new file with the following name: startSeleniumNode.cmd and add the following command in it:
java -jar "selenium-server-standalone-X.XX.X.jar" -role node -nodeConfig "nodeConfig.json" -Dwebdriver.chrome.driver="chromedriver.exe" -Dwebdriver.ie.driver="IEDriverServer.exe"
You can download the latest Chrome and IE WebDriver on the same page where you downloaded the Selenium Server Standalone:
http://www.seleniumhq.org/download/
Write some JAVA code :)
It is just an example, I'm sure that there are better solutions. For example you can use TestNG to create different tests, add parameters to your tests, or run your tests in parallel, etc... You can find more information on the TestNG site: http://testng.org/doc/index.html
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class ScreenshotMakerTest
{
public static void main(String [] args) throws IOException
{
// Init a new DesiredCapabilites which will setup the WebDriver to open a specific browser.
DesiredCapabilities dc = new DesiredCapabilities();
// Set the browser. If you want to open a Chrome, you can modify it to: DesiredCapabilites.chrome(); etc...
dc = DesiredCapabilities.internetExplorer();
// Set the Platform. It must be the same what you defined in the nodeConfig.json.
dc.setPlatform(Platform.WINDOWS);
// Set the version of the browser. If you didn't set any version in the nodeConfig.json, you can skip this line.
dc.setVersion("11");
// Create the WebDriver which will open the given browser on a Node
WebDriver driver = new RemoteWebDriver(new URL("IP_OF_THE_HUB:4444/wd/hub"), dc);
// Open a page
driver.get("http://google.com");
// Create screenshot about the current page
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Save the screenshot into a file
FileUtils.copyFile(scrFile, new File("c:\\screenshots\\screenshot.png"));
// Close the browser
driver.quit();
}
}
In this example, your code will open an Internet Explorer 11 on a Windows Node, open the http://google.com url and create a screenshot about it, and save it to c:/screenshots/screenshot.png.
Hope it helps.

Related

Selenium Chromedriver opens with data:, in navigation bar

if i open Chrome via chromedriver and navigate to a URL i only get a data:, in the navigation bar. All googled solutions (right chromedriverversion, protocoll in URL, etc.) didnt help me.
package de.vhv.selenium;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class OpenChromeAndNavigate {
#Test
public void test() {
System.setProperty("webdriver.chrome.driver", "C://vhventw//selenium//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.de");
}
}
In addition everything works if i add --headless and listen to the debugport. But i dont want to let it run headless.
package de.vhv.selenium;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class OpenChromeAndNavigate {
#Test
public void test() {
System.setProperty("webdriver.chrome.driver", "C://vhventw//selenium//chromedriver.exe");
WebDriver driver = new ChromeDriver(getDesiredCapabilities());
driver.get("https://www.google.de");
}
private ChromeOptions getDesiredCapabilities() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
// options.addArguments("--disable-extensions"); // disabling extensions
// options.addArguments("--disable-gpu"); // applicable to windows os only
// options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
// options.addArguments("--no-sandbox");
options.addArguments("--remote-debugging-port=9223");
return options;
}
}
Any ideas what i can try?
Setup:
Chrome Version = 71.0.3578.80
Chromedriver Version = 2.46.628402
I figured out, that the line
options.addArguments("--remote-debugging-port=9225");
fixed my problem. I already used it in headless runs to listen to the port and watch the headless run. But it fixed my problem with headfull runs.
return new ChromeDriver(getDesiredCapabilities());
private ChromeOptions getDesiredCapabilities() {
ChromeOptions options = new ChromeOptions();
//options.addArguments("--headless");
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox");
options.addArguments("--remote-debugging-port=9225");
return options;
}
You need to take care of a couple of things:
Not sure about your project structure but I will suggest to avoid the . character and the word selenium within the package name as in:
package de.vhv.selenium;
The Value part passed through System.setProperty() line containing the absolute path of chromedriver.exe should be expressed through escaped backslashes as:
System.setProperty("webdriver.chrome.driver", "C:\\vhventw\\selenium\\chromedriver.exe");
As per ChromeDriver - WebDriver for Chrome:
If you are using Chrome version 72, please download ChromeDriver 2.46 or ChromeDriver 72.0.3626.69
As per best practices:
Upgrade JDK to recent levels JDK 8u202.
Upgrade Selenium to current levels Version 3.141.59.
Upgrade ChromeDriver to current ChromeDriver v73.0.3683.68 level.
Keep Chrome version between Chrome v73 levels. (as per ChromeDriver v73.0.3683.68 release notes)
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.
Take a System Reboot.
Execute your #Test.
Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.
I was struggling with the same issue, then I realised that I forgot to start the test with :
$I->amOnPage('/');
definitely to try before digging deeper.

Geb test ignoring GebConfig.groovy file launched in IntelliJ

Running in IntelliJ IDEA.
GebConfig.groovy is in /src/test/resources.
I am using the Chrome driver.
When I type
System.setProperty("webdriver.chrome.driver", "my/path")
inside my spec file, and I right click and select run, the test works, meaning it opens Chrome and loads the page.
When I don't do that in the spec file, but just leave it in the GebConfig.groovy file, I get the error message "the page to the driver executable must be set".
There's an air-gap, so I can't copy-paste; I'll type as much as I can here:
GebConfig.groovy:
import org.openqa.selenium.chrome.ChromeDriver
...
environments {
chrome {
System.setProperty("webdriver.chrome.driver", "my/path")
driver = {new ChromeDriver()}
}
}
The spec file is really simple, like the example on GitHub
import LoginPage
import geb.spock.GebReportSpec
class LoginSpec extends GebReportSpec
{
// Works when I put this here, but I should not have to do this!
System.setProperty("webdriver.chrome.driver", "my/path")
def "user can log in" () {
when: "log in as me"
def loginPage = to LoginPage
loginPage.login("me")
then:
....
}
}
To fix your problem if you want to keep the path in the geb config, setting the path outside of the environment section like so should work:
import org.openqa.selenium.chrome.ChromeDriver
System.setProperty("webdriver.chrome.driver", "my/path")
//You can also set the driver up here as a default and running with an environment set will override it
driver = {new ChromeDriver()}
environments {
chrome {
driver = {new ChromeDriver()}
}
}
Personally I would avoid adding the driver path to the geb config and create a run configuration in intelliJ for running locally.
Right click the spec file > Click "Create 'nameOfMySpec'".
Now add your driver path to the VM parameters:
-Dgeb.env=chrome -Dwebdriver.chrome.driver=my/path
It's also worth considering a shell script that could then also be called via Jenkins etc:
mvn test -Dgeb.env=chrome -Dwebdriver.chrome.driver=my/path

Cannot execute testcase exported from selenium ide as java/junit4/remote control in eclipse ide

I am new to testing and i am trying to learn how to run recorded test cases in selenium ide in eclipse.
I recorded a testcase to search word selenium in the Google.
I exported it as java/junit4/remote control
Then i strated a new project in eclipse and add "java 4.12"and "selenium stand
alone server" external jar files.
I add the exporetd code to the project.
Then i started command prompt and executed selenium stand alone server.
Then i clicked run as junit in eclipse ide.
Firefox launched but an error is occured.
below is the code i executed:
package please;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.regex.Pattern;
public class please {
private Selenium selenium;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://www.google.lk/");
selenium.start();
}
#Test
public void testPlease() throws Exception {
selenium.open("/?gfe_rd=cr&ei=10SKWaOqJ46AuATcuKPAAg");
selenium.type("id=lst-ib", "selenium");
selenium.type("id=lst-ib", "selenium");
assertEquals("selenium - Google Search", selenium.getTitle());
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
This is what the result looks like
Recording tests via Selenium IDE is rarely a good option, mainly because many code snippets has to be refactored, lack of abstraction, modularity and so on (list is quite long actually). Looking at your code, I think that the problem is in the driver you are trying to use. According to this selenium mirror at Github. You should migrate to using WebDriver, instead of DefaultSelenium:
#deprecated The RC interface will be removed in Selenium 3.0. Please migrate to using WebDriver.
So, Selenium Interface and DefaultSelenium Class both belong to Selenium 1 and are deprecated. Selenium has advanced to Selenium 3 (WebDriver).
You will want to use the following classes as these are part of Selenium 3 (WebDriver). WebDriver is an interface used by various Selenium 3 drivers.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
Then you have various drivers that you can use. RemoteWebDriver / HtmlUnitDriver / FireFoxDriver / ChromeDriver / IEDriverServer etc. You will want to import the driver in your Java class.
Selenium selenium = new DefaultSelenium();
Becomes
WebDriver driver = new FireFoxDriver();
If your running the test using Selenium-Server try: (replace firefox with your browser version:
DesiredCapabilities capabillities= DesiredCapabilities.firefox();
capabillities.setCapability("platform", Platform.ANY);
capabillities.setCapability("name", "Testing Selenium-2 Remote WebDriver");
WebDriver driver = new RemoteWebDriver( new URL("http://localhost:4444/wd/hub"), capabillities);
driver.get("http://www.google.com");
assertEquals("Google", this.driver.getTitle());

selenium grid connction with autoit not working?

selenium grid connection with auto it not working ?
#daluudaluu/PartialSeleniumGridIntegrationWithAutoItExample.java
Last active a year ago
Embed
Download ZIP
Code Revisions 2 Forks 1
Partial Selenium Grid integration support with tools like AutoIt, Sikuli, etc.
Raw
PartialSeleniumGridIntegrationWithAutoItExample.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.*;
import java.net.URL;
public class DemoTest {
public WebDriver driver;
public DesiredCapabilities capabilities;
#Before
public void setUp() throws Exception {
capabilities = DesiredCapabilities.firefox();
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub" ), capabilities);
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void test() throws Exception {
// Use RemoteWebDriver, grab actual node host info
driver.get("http://www.google.com");
String sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
//grid info extractor from: https://gist.github.com/krmahadevan/1766772
String nodeHost = GridInfoExtracter.getHostNameAndPort("localhost", 4444, sessionId)[0];
System.out.println("Extracted hostname: "+nodeHost);
// Now use node host info to handle running AutoIt on that specific node, assuming all needed files deployed to all nodes
// Case 1 - PSExec.exe from Windows host (that is executing this Selenium code) to Selenium node that is Windows host
//String psexecCmd = "C:\\LocalMachinePathTo\\psexec.exe \\\\%s -u %s -p %s -i C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe";
//Process p = Runtime.getRuntime().exec(String.format(psexecCmd,nodeHost,"jdoe","hisPassword"));
//p.waitFor();
// Case 2 - winexe from *nix host (that is executing this Selenium code) to Selenium node that is Windows host
// Example reference: http://secpod.org/blog/?p=661
//String winexeCmd = "/LocalMachinePathTo/winexe -U domainName/jdoe%hisPassword //"+nodeHost+" C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe";
//Process p = Runtime.getRuntime().exec(winexeCmd);
//p.waitFor();
// Case 3 - have SSH installed on Windows-based Selenium nodes, now just connect to node host via SSH to run a command, i.e. execute AutoIt script binary
// no sample code given for Java, but maybe this gives you ideas on Java SSH connection:
// http://stackoverflow.com/questions/995944/ssh-library-for-java
// Case 4 - if you have implemented a custom web service (XML-RPC/SOAP/REST) for AutoIt that listens for requests/commands
// just connect to it via (Java) HTTP library to "http://"+nodeHost+"/someWebServicePath/someCommand" (via GET or POST)
// details not covered, this is just an example. Most people won't be taking this route due to customization & complexity in
// building the web service first
// Case 5 - using AutoItDriverServer that is also running on Selenium nodes
//DesiredCapabilities autoitCapabilities = new DesiredCapabilities();
//autoitCapabilities.setCapability("browserName", "AutoIt");
//WebDriver autoitDriver = new RemoteWebDriver(new URL("http://"+nodeHost+":4723/wd/hub"), autoitCapabilities);
//autoitDriver.findElement(By.id("133")).click();
//and whatever other AutoItX commands to call that you normally have in the AutoIt script that you compile into binary
//for more ideas on AutoIt commands issued as WebDriver commands with respect to Selenium integration, see:
//https://github.com/daluu/AutoItDriverServer/blob/master/sample-code/SeleniumIntegrationWithAutoItDriver.py
//or if you are old school, and want to do that same approach even with AutoItDriverServer,
// assuming you have first set AutoItScriptExecuteScriptAsCompiledBinary to True in autoit_options.cfg file before starting AutoItDriverServer:
//((JavascriptExecutor) autoitDriver).executeScript("C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe");
// Case for Sikuli integration, using https://github.com/enix12enix/sikuli-remote-control
//RemoteScreen rs = new RemoteScreen(nodeHost);
//rs.setMinSimilarity(0.9);
//rs.click("D://test.png");
}
}

How to set the firefox profile at the node end in remote webdriver/grid configuration

It is always suggested to set the firefox profile in DesiredCapabilities and pass that through the wire ,where the hub is running . Like below
DesiredCapabilities caps = DesiredCapabilities.firefox();
FirefoxProfile profile=new FirefoxProfile(new File("Local Path to firefox profile folder"));
caps.setCapability(FirefoxDriver.PROFILE, profile);
URL url = new URL("http://localhost:4444/wd/hub");
WebDriver driver= new RemoteWebDriver(url,caps );
But sending the huge 87-90 mb profile info to hub over http ,for each selenium test case slowing down the test case execution .
I have tried configuring the grid node with "Dwebdriver.firefox.profile=E:\\Firefox_Profile_Location":"", property in json node config file like below.
{
"configuration":
{
.//Other Settings
.//Other Settings
.//Other Settings
"Dwebdriver.firefox.profile=E:\\Firefox_Profile_Location":"",
"maxSession":7,
"registerCycle":5000,
"register":true
},
"capabilities":
[
{"browserName":"firefox",
"seleniumProtocol":"WebDriver",
"maxInstances":5,
"platform":"VISTA"
}
]
}
But running with the above configuration is throwing below error .
WebDriverException: Firefox profile 'E:\Firefox_Profile_Location'
named in system property 'webdriver.firefox.profile' not found
Advanced thanks for any help on how to configure the firefox profile from the node side .
You need to provide the profile in the capabilities object as a base64 encoded zip:
var fs = require('fs');
capabilities: [
{
browserName: 'firefox',
seleniumProtocol: 'WebDriver',
maxInstances: 5,
platform: 'VISTA',
firefox_profile: new Buffer(fs.readFileSync("./profile.zip")).toString('base64')
}
]
Moreover Firefox creates the missing files for a given profile. So you should keep just the necessary files in the profile depending on your needs:
Preferences: user.js
Passwords: key3.db
logins.json
Cookies: cookies.sqlite
Certificate: cert8.sqlite
Extensions: extensions/
I think you'll have to use firefox profile name and not the location.
"webdriver.firefox.profile":"default"
Have a look at this and this and this
If you want know how to create a profile follow this and this