“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
PhantomJS is colloquially known as the Browser without interfaces. PhantomJS is a WebKit-based JavaScript API. It uses QtWebKit as its core browser functionality, using WebKit to compile, interpret and execute JavaScript code. PhantomJS, the headless browser, is one of the most popular Python crawlers. Of course, there are other headless browsers.
purpose
PhantomJS can do a lot of things, anything you can do in a WebKit-based browser, it can do. Not only is it an invisible browser, it provides CSS selectors, support for Web standards, DOM manipulation, JSON, HTML5, Canvas, SVG, etc., but it also provides file I/O operations so that you can read and write files to the operating system, etc. Here I’m using it to take a screenshot of a chart generated by Echarts.
The implementation of
Can be downloaded from the website: phantomjs.org/download.ht… , JavaScript Standard Reference Tutorial (alpha).
In the examples folder it has written a lot of demo for reference and reference.
1. Download the Echarts file
2. Write the script code, first introduce the module and generate page, because it is input from the command line, so need to obtain system.args
var page = require('webpage').create();
var system = require('system');
var exportImg = system.args[1];
var data = JSON.parse(window.atob(system.args[2]));
Copy the code
Write HTML tags in page.content as follows:
image.png
That’s where all the HTML tags are written.
InjectJs (“./echarts.min.js”);
Then you need to write the Echarts configuration item in: Page. Evaluate
image.png
Finally, save as a picture and exit
page.render(exportImg);
phantom.exit();
Copy the code
The command is./ phantomjs. /test.js [image name] [parameter]. This generates the image.
Screenshot page:
var page = require('webpage').create(),
server = 'https://www.baidu.com';
page.open(server, function (status) {
page.render('xx.png');
phantom.exit();
});
Copy the code
So you can screenshot baidu web pages. Var server = require(‘webserver’).create(); To start a service and listen to receive parameters to render HTML and take screenshots.
There are many examples to refer to in the demo, this is an interesting tool that can be used to generate report images on the server side. Here said relatively shallow, mainly is a long experience, more view demo and Ruan yifeng tutorial.