简体   繁体   中英

The difference between normal and headless browser

Often I meet PhantomJS to run headless browser , headless browser .

What's the difference between normal (user invoked or regular Selenium webdriver code invoked) and a headless browser?

Besides all, I'd like to make things clear on these browser features:

  • headers
  • local storage
  • cookie

A headless browser is by definition a web browser without a graphical user interface(GUI).

Normally, interaction with a website are done with mouse and keyboard using a browser with a GUI, While most headless browser provides an API to manipulate the page/DOM, download resources etc. So instead of, for example, actually clicking an element with the mouse, a headless browser allows you to click an element by code.

Example of interacting with a page using PhantomJS:

    page.evaluate(function() {
        //Fill in form on page
        document.getElementById('Name').value = 'John Doe'; 
        document.getElementById('Email').value = 'john.doe@john.doe';
        //Submit
        $('#SubmitButton').click();
    });

Headers, Local storage and Cookies work the same way in most headless browsers as they do in regular browsers with a GUI if they are implemented. PhantomJS and HtmlUnit has support for all of these features.

In PhantomJS, you may also add your own cookies. For example, you may copy a cookie from chrome and programmatically add it to the phantomjs browser at runtime. It will automatically be added to page requests for a specific domain.

Adding a cookie to a page before loading it

var webPage = require('webpage');
var page = webPage.create();

phantom.addCookie({
  'name'     : 'Valid-Cookie-Name',   /* required property */
  'value'    : 'Valid-Cookie-Value',  /* required property */
  'domain'   : 'localhost',
  'path'     : '/',                /* required property */
  'httponly' : false,
  'secure'   : false,
  'expires'  : (new Date()).getTime() + (1000 * 60 * 60)   /* <-- expires in 1 hour */
});
page.open('localhost', function (status) {
//Cookie automatically added to request headers for localhost
...
});

For some runnable examples using PhantomJS, see The phantomjs examples page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM