您的位置:首页 > Web前端 > JavaScript

使用 PhantomJS + GM 实现网页中校检图片的截取

2017-06-01 10:15 211 查看
最近公司项目需要,需要写个类似于爬虫的东东。

这里只介绍一个小功能点的实现:抓取校检图片

注:所用网站只是示例,因为其校检图片有代表性,能充分提现 phantomJS 这类 headless webbrowser 的优势。

开撸:var phantom = require('phantom');
var gm=require('gm');

phantom.create().then(function(ph) {
ph.createPage().then(function(page) {

page.property('viewportSize',{width: 1920, height: 1080});

page.property("customHeaders",{
"Cache-Control":"no-cache",
"Pragma":"no-cache",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0",
"Upgrade-Insecure-Requests":1
});

page.property("onConsoleMessage",function(msg){console.log(msg);});

page.property("onResourceReceived",function(response){
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
});

page.property("onUrlChanged",function(newURL){
//console.info("zq:"+newURL);
});

page.open('https://passport.zhaopin.com/org/login').then(function(status) {

if(status === "success")
{

page.evaluate(function(){
var triggerBt1=document.getElementById("CheckCodeCapt");
triggerBt1.click();//点击进入登录界面

/*for(var key in triggerBt1)
{
console.info(key+" : "+triggerBt1[key]);
}*/

});

setTimeout(function () {
var picName="zhilianPicRaw.jpeg";
var whitePic="whitePic.jpg";
page.render(picName,{format: 'jpeg', quality: '100'}); //截图
console.info("raw picture catched!");

var picOutName="zhilianPic.jpeg";
//图片处理-剪裁图片
gm(picName).crop(293,190,823,363).write(picOutName,function(err){
if(err)
{
console.info(err);
}
else
{
console.info("picture sliced!");
//合并图片
gm().in('-page','+0+0').in(picOutName).in('-page','+0+0').in(whitePic).mosaic().write(picOutName,function(err){
if(err){
console.info(err);
}
else
{
console.info("picture parsed!");
}
});
}
});

}, 1000);

//ph.exit();
}

/*page.property('content').then(function(content) {
console.log(content);
page.close();
ph.exit();
});*/
})
});
});

注意,当所有操作完成后,别忘记调用:ph.exit() 释放内存。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息