Tag Archives: Java

How to use Selenium headless

In Java and Python, this merely requires using a headless browser like PhantomJS.

Java

import org.openqa.selenium.phantomjs.PhantomJSDriver;
Webdriver driver = new PhantomJSDriver();

Python

from selenium import webdriver
driver = webdriver.PhantomJS()

C#

The PhantomJS classes are no longer supported in C#, so you need to use Firefox or Chrome in headless mode instead.

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
IWebDriver driver;
FirefoxOptions options = new FirefoxOptions();
options.AddArguments("--headless");
driver = new FirefoxDriver(options);

How to take a screenshot in Selenium

Java

In Java, cast the Webdriver to a TakeScreenshot and then call its takeScreenshotAs() method.
This will create a File object, which you can then copy to a real disk file.

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Python

In Python, use the save_screenshot() method of the webdriver.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.google.com/')
driver.save_screenshot("c:\\tmp\\screenshot.png")

C#

In C#, cast the driver to a ITakesScreenshot and then call its GetScreenshot method.
You can then call SaveAsFile() on the returned Screenshot object.

Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile(@"C:\tmp\screenshot.png", System.Drawing.Imaging.ImageFormat.Png);

Downloading a Web page in Java using a java.net.Socket

import java.io.*;
import java.net.*;
 
public class SocketHTTPClient {
    public static void main(String[] args) {
         
        String hostName = "www.martinbroadhurst.com";
        int portNumber = 80;
 
        try {
            Socket socket = new Socket(hostName, portNumber);
            PrintWriter out =
                new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in =
                new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            out.println("GET / HTTP/1.1\nHost: www.martinbroadhurst.com\n\n");
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        } 
    }
}