• phantomJs 快速入门学习 了解大概


    1、hellow程序

    一个永远的开头,创建一个文件hello.js。内容如下

    //hello.js
    //在窗口输出信息 console.log('Hellow ,Word');
    //退出程序,每个脚本必须有 phantom.exit();

      运行程序

    2、页面加载

    创建一个文件myload.js

    webpage是phantomjs的最重要的一个函数,用于初始化一个无头浏览器实例。

    //myload.js
    //创建一个无头浏览器实例 var page = require('webpage').create();
    //open函数:第一个参数为要访问的url地址,第二个参数为访问url后的回调函数,function参数默认为访问url后的状态值 page.open('http://example.com',function(status){ console.log("logging stats :"+status); if (status == 'success'){ page.render('examp.jpg'); }
    //如果没有,程序就不会退出 phantom.exit(); }

      运行程序,此时c:myjs下生成了examp.jpg图片

     3、加载速度测试

    创建一个文件loadspeed.js,system是系统涵数,可以与系统环境做交互,system.args为系统传入的参数。

    //loadspeed.js
    var page = require('webpage').create(),
      system = require('system'),
      t, address;
    
    if (system.args.length === 1) {
      console.log('Usage: loadspeed.js <some URL>');
      phantom.exit();
    }
    
    t = Date.now();
    address = system.args[1];
    page.open(address, function(status) {
      if (status !== 'success') {
        console.log('FAIL to load the address');
      } else {
        t = Date.now() - t;
        console.log('Loading ' + system.args[1]);
        console.log('Loading time ' + t + ' msec');
      }
      phantom.exit();
    });
    

      运行程序

    4、执行js代码,evaluate函数用来执行js代码

    //executecode.js
    page = require('webpage').create();
    // Open打开请求的URL page.open('http://example.com/',function(status){
          // evaluate对返回的文档执行JS程序 var title = page.evaluate(function(){ return document.title; }); console.log(title); phantom.exit(); })

      运行程序

    5、console.log在evaluate函数中是不能输出的。onConsoleMessage事件监听evaluate中的所有console.log.

    var page = require('webpage').create();
    page.onConsoleMessage = function(msg) {
      console.log('Page title is ' + msg);
    };
    page.open(
    'http://example.com/'
    , function(status) { page.evaluate(function() { console.log(document.title); }); phantom.exit(); });

      

    6、网络请求与响应

    当发起一个远程服务器的页面请求的时候,请求与响应都能通过onResourceRquested与onResourceReceived的回调函数跟踪

    var page = require('webpage').create();
    page.onResourceRequested = function(request) {
      console.log('Request ' + JSON.stringify(request, undefined, 4));
    };
    page.onResourceReceived = function(response) {
      console.log('Receive ' + JSON.stringify(response, undefined, 4));
    };
    page.open('http://example.com/');
    

      

  • 相关阅读:
    while 循环 。。
    数据运算,运算符
    字符串常用操作
    列表常用操作
    三级菜单
    杂七杂八
    简单的登陆程序001
    猜年龄游戏
    实现密文输入密码
    使用urllib2打开网页的三种方法
  • 原文地址:https://www.cnblogs.com/kongzhagen/p/6272985.html
Copyright © 2020-2023  润新知