zoukankan      html  css  js  c++  java
  • Phantomjs 一些简单实用

      Phantomjs是一个基于webkit的服务器端JavaScirpt API。它全面支持web而不需要浏览器支持,并且原生支持web的各种标准:DOM处理,CSS选择器,JSON,Canvas和SVG。可以用于页面自动化、网络检测、网页截屏、无界面测试等。

      1、使用

      新建一个hi.js文件,里面写入js脚本,并且以phantom.exit();结尾, 执行DOS命令:phantomjs hi.js即可执行文件内脚本内容。

      2、参数处理

      参考phantomjs安装目录下examples中的arguments.js,DOS命令:phantomjs examples/arguments.js foo bar baz

      它将输出 :

        0: foo
        1: bar
        2: baz

      3、页面截图

      参考代码(将请求www.baidu.com网站并将截图保存成baidu.png):

    var page = require('webpage').create();
    page.open('http://www.baidu.com', function () {
      page.render('html/baidu.png');
      phantom.exit();
    });

      4、Cookie处理

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

    var fs = require('fs');
    phantom.addCookie({
      'name' : 'province',
      'value': 'provinceName%22%3A%22%u5317%u4EAC',
      'domain': 'baidu.com'
    });
    phantom.addCookie({
      'name' : 'addrDetail',
      'value': '%7B%22detail%22%3A%22%u5317%u4EAC%22%2C%22detailId%22%3A2%2C%22detailCode%22%3A110000%7D',
      'domain': 'baidu.com'
    });
    page.open('http://www.baidu.com', function(status){
      if(status !== 'success'){
        console.log('Unable to post!');
      }else{ // 将页面保存成本地文件,并将所有script脚本替换为空字符,
        fs.write('html/baidu.html',page.content.replace(/<script[^>]*>([sS]*?)</script>/gm,""),'w');
      }
      phantom.exit();
    });

      5、文件处理

    var filePath = 'test.js';//文件路径
      var fs = require("fs");
      //判断文件是否存在,是文件还是文件夹
      if( fs.exists(filePath) && fs.isFile(filePath) ) {
        var ins = fs.open(filePath, 'r');//打开文件
        while(!ins.atEnd()) {//循环读取文件内容
        var buffer = ins.readLine();//一行行的读取
        console.log(buffer);
      }
    }

      

  • 相关阅读:
    时间序列模型文章收集
    因果推断文章收集
    Git常用命令
    redis配置
    团队作业2:需求分析&原型设计
    团队项目作业1-团队展示与选题
    结对编程1-模块化
    个人作业2:APP案例分析
    为农三载
    面试题随记一
  • 原文地址:https://www.cnblogs.com/icerainsoft/p/phantomjs.html
Copyright © 2011-2022 走看看