phontomjs webPage模块方法

article/2025/10/28 20:52:27

随时随地技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

addCookie

addCookie(Cookie) {boolean}

Introduced: PhantomJS 1.7

Add a Cookie to the page. If the domain does not match the current page, the Cookie will be ignored/rejected. Returns true if successfully added, otherwise false.

Examples

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'     : '/foo',                /* required property */'httponly' : true,'secure'   : false,'expires'  : (new Date()).getTime() + (1000 * 60 * 60)   /* <-- expires in 1 hour */

childFramesCount

Deprecated.

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.childFramesCount example.

childFramesName

Deprecated.

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.childFramesName example.

clearCookies

clearCookies() {void}

Introduced: PhantomJS 1.7

Delete all Cookies visible to the current URL.

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.clearCookies example.

close

close() {void}

Introduced: PhantomJS 1.7

Close the page and releases the memory heap associated with it. Do not use the page instance after calling this.

Due to some technical limitations, the web page object might not be completely garbage collected. This is often encountered when the same object is used over and over again. Calling this function may stop the increasing heap allocation.

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.close example.

currentFrameName

Deprecated.

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.currentFrameName example.

deleteCookie

deleteCookie(cookieName) {boolean}

Introduced: PhantomJS 1.7

Delete any Cookies visible to the current URL with a ‘name’ property matching cookieName. Returns true if successfully deleted, otherwise false.

Examples

var webPage = require('webpage');
var page = webPage.create();page.deleteCookie('Added-Cookie-Name');

evaluateAsync

evaluateAsync(function, [delayMillis, arg1, arg2, ...]) {void}

Evaluates the given function in the context of the web page, without blocking the current execution. The function returns immediately and there is no return value. This is useful to run some script asynchronously.

The second argument indicates the time (in milliseconds) before the function should execute. The remaining arguments are passed to the function, as with evaluate. You must specify a delay (which can be 0) if you want to pass in any arguments.

Examples

Asynchronous AJAX

var webPage = require('webpage');
var page = webPage.create();page.open("", function(status) {page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {page.evaluateAsync(function() {$.ajax({url: "api1", success: function() {}});});page.evaluateAsync(function(apiUrl) {$.ajax({url: apiUrl, success: function() {}});}, 1000, "api2");});
});

evaluateJavaScript

evaluateJavaScript(str)

Evaluate a function contained in a string.

evaluateJavaScript evaluates the function defined in the string in the context of the web page. It is similar to evaluate.

Examples

Set a variable and log it from the web page

This example passes a constant value from phantomjs to the window object in the context of the web page, and then logs that value.

var webPage = require('webpage');
var page = webPage.create();page.onConsoleMessage = function(msg) {console.log('The web page said: ' + msg);
};page.open('http://phantomjs.org/', function(status) {var script1 = "function(){ window.phantomVar='phantomjs made me do it!'; }";var script2 = "function(){ console.log(window.phantomVar); }";page.evaluateJavaScript(script1);page.evaluateJavaScript(script2);phantom.exit();
});

Notice that str must contain the text of a function declaration. The declared function is invoked immediately.

If you try to use it simply to define a variable like this. it won’t work.

  page.evaluateJavaScript("window.phantomVar='phantomjs made me do it!';"); /*wrong*/

If you try this you’ll get an error message like this:

SyntaxError: Expected token ')'phantomjs://webpage.evaluate():1 in evaluateJavaScript

Extract the phantomjs.org website’s logo url

var webPage = require('webpage');
var page = webPage.create();page.onConsoleMessage = function(msg) {console.log('CONSOLE: ' + msg);
};page.open('http://phantomjs.org/', function(status) {var logoUrl = page.evaluateJavaScript('function(){return document.body.querySelector("img").src;}');console.log(logoUrl); // http://phantomjs.org/img/phantomjs-logo.pngphantom.exit();});

evaluate

evaluate(function, arg1, arg2, ...) {object}

Evaluates the given function in the context of the web page. The execution is sandboxed, the web page has no access to the phantom object and it can’t probe its own setting.

Examples

Get the page title from Bing.com (1)

var webPage = require('webpage');
var page = webPage.create();page.open('http://m.bing.com', function(status) {var title = page.evaluate(function() {return document.title;});console.log(title);phantom.exit();});

Get the page title from Bing.com (2)

As of PhantomJS 1.6, JSON-serializable arguments can be passed to the function. In the following example, the text value of a DOM element is extracted.

The following example achieves the same end goal as the previous example but the element is chosen based on a selector which is passed to the evaluate call:

page.open('http://m.bing.com', function(status) {var title = page.evaluate(function(s) {return document.querySelector(s).innerText;}, 'title');console.log(title);phantom.exit();});

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

Any console message from a web page, including from the code inside evaluate, will not be displayed by default. To override this behavior, use the onConsoleMessage callback. The first example can be rewritten to:

Get the page title from Bing.com and print it inside evaluate

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

getPage

getPage(windowName)

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.getPage example.

goBack

goBack()

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.goBack example.

goForward

goForward()

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.goForward example.

go

go(index)

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.go example.

includeJs

includeJs(url, callback) {void}

Includes external script from the specified url (usually a remote location) on the page and executes the callback upon completion.

Examples

var webPage = require('webpage');
var page = webPage.create();page.includeJs(// Include the https version, you can change this to http if you like.'https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js',function() {(page.evaluate(function() {// jQuery is loaded, now manipulate the DOMvar $loginForm = $('form#login');$loginForm.find('input[name="username"]').value('phantomjs');$loginForm.find('input[name="password"]').value('c45p3r');}))}
);

injectJs

injectJs(filename) {boolean}

Injects external script code from the specified file into the page (like page.includeJs, except that the file does not need to be accessible from the hosted page).

If the file cannot be found in the current directory, libraryPath is used for additional look up.

This function returns true if injection is successful, otherwise it returns false.

Examples

Inject do.js file into phantomjs.org page

var webPage = require('webpage');
var page = webPage.create();page.open('http://www.phantomjs.org', function(status) {if (status === "success") {page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {if (page.injectJs('do.js')) {var title = page.evaluate(function() {// returnTitle is a function loaded from our do.js file - see belowreturn returnTitle();});console.log(title);phantom.exit();}});}
});

Where do.js is simply:

window.returnTitle = function() {return document.title;
};

The console log will be:

"PhantomJS | PhantomJS"

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

openUrl

openUrl(url, httpConf, settings)

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.openUrl example.

open

open(url, callback) {void}

open(url, method, callback) {void}

open(url, method, data, callback) {void}

open(url, settings, callback) {void}

Opens the url and loads it to the page. Once the page is loaded, the optional callbackis called using page.onLoadFinished, with the page status ('success' or 'fail') provided to it.

Examples

GET google.com and report “success” or “fail”

var webPage = require('webpage');
var page = webPage.create();page.open('http://www.google.com/', function(status) {console.log('Status: ' + status);// Do other things here...
});

POST data to google.com and report “success” or “fail”

As of PhantomJS 1.2, the open function can be used to request a URL with methods other than GET. This syntax also includes the ability to specify data to be sent with the request. In the following example, we make a request using the POST method, and include some basic data.

var webPage = require('webpage');
var page = webPage.create();
var postBody = 'user=username&password=password';page.open('http://www.google.com/', 'POST', postBody, function(status) {console.log('Status: ' + status);// Do other things here...
});

POST json data to your.custom.api in utf-8 encoding

As of PhantomJS 1.9, the open function can get an object of settings. and with a use of “encoding” key, you can set the custom encoding to your app. In this example, we’ve set the encoding to UTF8, and set the Content-Type header to application/json for making our server know the request has information in json format and not in urlencoded format.

var webPage = require('webpage');
var page = webPage.create();
var settings = {operation: "POST",encoding: "utf8",headers: {"Content-Type": "application/json"},data: JSON.stringify({some: "data",another: ["custom", "data"]})
};page.open('http://your.custom.api', settings, function(status) {console.log('Status: ' + status);// Do other things here...
});

release

release() {void}

Stability: DEPRECATED - Use page.close

Releases memory heap associated with this page. Do not use the page instance after calling this.

Due to some technical limitations, the web page object might not be completely garbage collected. This is often encountered when the same object is used over and over again. Calling this function may stop the increasing heap allocation.

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.release example.

reload

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.reload example.

renderBase64

renderBase64(format)

Renders the web page to an image buffer and returns the result as a Base64-encoded string representation of that image.

Supported formats

  • PNG
  • GIF
  • JPEG

Examples

var webPage = require('webpage');
var page = webPage.create();page.viewportSize = {width: 1920,height: 1080
};page.open('http://phantomjs.org', function (status) {var base64 = page.renderBase64('PNG');console.log(base64);phantom.exit();
});

renderBuffer

renderBuffer(format, quality)

Renders the web page to an image buffer which can be sent directly to a client (e.g. using the webserver module)

Supported formats

  • PNG
  • GIF
  • JPEG

Examples

var server = require('webserver').create();var listening = server.listen(8001, function(request, response) {var url = "http://phantomjs.org", format = 'png', quality = -1;var page = require('webpage').create();page.viewportSize = {width: 800,height: 600};page.open(url, function start(status) {// Buffer is an Uint8ClampedArrayvar buffer = page.renderBuffer(format, quality);response.statusCode = 200;response.headers = {"Cache": "no-cache","Content-Type": "image/" + format};page.close();// Pass the Buffer to 'write' to send the Uint8ClampedArray to the clientresponse.write(buffer);response.close();});});

render

render(filename [, {format, quality}]) {void}

Renders the web page to an image buffer and saves it as the specified filename.

Currently, the output format is automatically set based on the file extension.

Supported formats

  • PDF
  • PNG
  • JPEG
  • BMP
  • PPM
  • GIF support depends on the build of Qt used

Quality

An integer between 0 and 100.

The quality setting only has an effect on jpeg and png formats. With jpeg, it sets the quality level as a percentage, in the same way as most image editors. (The output file always has 2x2 subsampling.) A level of 0 produces a very small, very low quality file, and 100 produces a much larger, high-quality file. The default level is 75. With png, it sets the lossless (Deflate) compression level, with 0 producing the smallest files, and 100 producing the largest. However, the files look identical, and are always true-colour.

Examples

var webPage = require('webpage');
var page = webPage.create();page.viewportSize = { width: 1920, height: 1080 };
page.open("http://www.google.com", function start(status) {page.render('google_home.jpeg', {format: 'jpeg', quality: '100'});phantom.exit();
});

More information

The image generation code (except for PDF output) uses QImage from the Qt framework, documented at http://doc.qt.io/qt-5/qimage.html#save.

sendEvent

Sends an event to the web page.

1.7 implementation source.

The events are not synthetic DOM events, each event is sent to the web page as if it comes as part of user interaction.

Mouse events

sendEvent(mouseEventType[, mouseX, mouseY, button='left'])

The first argument is the event type. Supported types are 'mouseup''mousedown''mousemove''doubleclick' and 'click'. The next two arguments are optional but represent the mouse position for the event.

The button parameter (defaults to left) specifies the button to push.

For 'mousemove', however, there is no button pressed (i.e. it is not dragging).

Keyboard events

sendEvent(keyboardEventType, keyOrKeys, [null, null, modifier])

The first argument is the event type. The supported types are: keyupkeypress and keydown. The second parameter is a key (from page.event.key), or a string.

You can also indicate a fifth argument, which is an integer indicating the modifier key.

  • 0: No modifier key is pressed
  • 0x02000000: A Shift key on the keyboard is pressed
  • 0x04000000: A Ctrl key on the keyboard is pressed
  • 0x08000000: An Alt key on the keyboard is pressed
  • 0x10000000: A Meta key on the keyboard is pressed
  • 0x20000000: A keypad button is pressed

Third and fourth argument are not taken account for keyboard events. Just give null for them.

Examples

Simulate a shift+alt+A keyboard combination

var webPage = require('webpage');
var page = webPage.create();page.sendEvent('keypress', page.event.key.A, null, null, 0x02000000 |

setContent

Introduced: PhantomJS 1.8

Allows to set both page.content and page.url properties.

The webpage will be reloaded with the new content and the current location set as the given url, without any actual http request being made.

Examples

var webPage = require('webpage');
var page = webPage.create();
var expectedContent = '<html><body><div>Test div</div></body></html>';
var expectedLocation = 'http://www.phantomjs.org/';
page.setContent(expectedContent, expectedLocation);

stop

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.stop example.

switchToChildFrame

switchToChildFrame(frameName) or switchToChildFrame(framePosition)

Deprecated.

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.switchToChildFrame example.

switchToFocusedFrame

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.switchToFocusedFrame example.

switchToFrame

if the page have othe frame, you can use switchToFrame(frameName) or switchToFrame(framePosition) to exchange it.Other similar methods are switchToChildFrame(),switchToFocusedFrame,switchToMainFrame and switchToParentFrame

Examples

var webPage = require('webpage');
var page = webPage.create();
page.open('http://www.sample.com',function(status){if(status!== 'success'){console.log('Unable to access network');}else{page.switchToFrame('framwName/framwPosition');console.log(page.frameContent);phantom.exit();}
});

switchToMainFrame

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.switchToMainFrame example.

switchToParentFrame

Examples

var webPage = require('webpage');
var page = webPage.create();
// @TODO: Finish page.switchToParentFrame example.

uploadFile

uploadFile(selector, filename)

Uploads the specified file (filename) to the form element associated with the selector.

This function is used to automate the upload of a file, which is usually handled with a file dialog in a traditional browser. Since there is no dialog in this headless mode, such an upload mechanism is handled via this special function instead.

Examples

var webPage = require('webpage');
var page = webPage.create();page.uploadFile('input[name=image]', '/path/to/some/photo.jpg');


http://chatgpt.dhexx.cn/article/S4X3KP2U.shtml

相关文章

webpage基本使用

webpack的基本使用 一.安装webpack (1) 打开项目目录终端&#xff0c;输入命令: npm install webpack webpack-cli -D (2) 然后在项目根目录中&#xff0c;创建一个 webpack.config.js 的配置文件用来配置webpack 在 webpack.config.js 文件中编写代码进行webpack配置&#…

集电极开路的门电路 OC门

当几个与非门输出端用导线直接相连时&#xff0c;可能会出现几个门的电流冲到同一个二极管上&#xff0c;造成烧坏&#xff0c;所以用集电极开路的门电路&#xff0c;统一在输出端接外接电源。 单个门电路的电路图 符号 使用时&#xff0c;一般将几个输出段导线连接&#xff0c…

OC门电路

灰度变换处理方法 什么是OC门 即集电极开路门电路&#xff0c;OD门&#xff0c;即漏极开路门电路&#xff0c;必须外界上拉电阻和电源才能将开关电平作为高低电平用。否则它一般只作为开关大电压和大电流负载&#xff0c;所以又叫做驱动门电路。 oc门电路工作原理  实际使用中…

一文搞懂OC门、OD门及其作用

我们先给出OC门、OD门的定义&#xff0c;然后从原理出发&#xff0c;介绍OC门、OD门的作用。 1 什么是OC门、OD门 OC门&#xff08;Open Collector Gate&#xff09;&#xff1a;集电极开路门&#xff0c;如图1所示&#xff0c;当N1导通时&#xff0c;输出低电平&#xff1b;当…

TTL反相器、OC门、TS门、推挽输出、开漏输出

TTL反相器 这是一个TTL反相器&#xff0c;这是经过了很多工程师多种设计最终沉淀出来的电路&#xff0c;这个电路是比较成熟的。我们只需要对这个电路进行解析即可&#xff0c;不需要再去研究当初是如何设计出来的。 学过CMOS应该知道&#xff0c;右侧的输出级其实也是个推挽输…

理解OC门

注&#xff1a;本文转载自新浪博客。 什么是集电极开路&#xff08;OC&#xff09;&#xff1f; 我们先来说说集电极开路输出的结构。集电极开路输出的结构如图1所示&#xff0c;右边的那个三极管集电极什么都不接&#xff0c;所以叫做集电极开路&#xff08;左边的三极管为反相…

OC门

reference: http://www.cnblogs.com/xiangxiangyuan/p/3787831.html (其他总结也精彩&#xff09; OC&#xff08;open collector)门&#xff0c;又称 集电极开路门。 OD门&#xff08;Open Drain&#xff0c; 漏极开路门&#xff0c;对场效应管而言&#xff09;。实际使用中&a…

Golang 切片

文章目录 和数组的区别声明空切片可以和nil相等切片长度,容量切片增加元素切片删除元素切片排序切片截取范围多维切片 和数组的区别 1.数组是定长,切片不是 2.数组是值传递&#xff0c;切片不是 声明 1.通过var声明 2.简短声明 package mainimport "fmt"func mai…

Java 各种 切片 操作(Array String List)

在python的 [xx:xx] 切片操作中快乐之后&#xff0c;返回Java变成发现这个习惯保持保持下去了&#xff01;&#xff0c;可惜JDK并不认账反手给我爆了两个红JDK&#xff1a;这是别人的香水味&#xff01; 所以这次总结一下在Java中各种数据类型的切片操作如何实现&#x…

python切片操作方法小总结

文章参考自&#xff1a;link. python切片的详细总结 最近学习python切片&#xff0c;时而醍醐灌顶时而云里雾里&#xff0c;今天终于弄清楚了 python切片 里面自己经常疑惑的地方&#xff0c;记录一下&#xff0c;方便以后查看。 一、切片的2种索引方向 如果掌握切片方法&a…

Python中numpy数组切片

参考Python中numpy数组切片 - 云社区 - 腾讯云 1、基本概念 Python中符合切片并且常用的有&#xff1a;列表&#xff0c;字符串&#xff0c;元组。 下面那列表来说明&#xff0c;其他的也是一样的。 格式&#xff1a;[开头&#xff1a;结束&#xff1a;步长] 开头&#xff1a…

python切片

前言 所谓切片就是在某个数据里提取需要的部分&#xff0c;提取到的是某个索引下的值&#xff0c;或者索引区间的值 一、认识切片 ① 支持切片操作的数据类型有&#xff1a; list&#xff08;列表&#xff09;&#xff0c;tuple&#xff08;元祖&#xff09;&#xff0c;st…

字符串的切片操作

字符串的切片操作&#xff1a; 1.知识点&#xff1a; str[start: end:方向和步长]&#xff0c;没有方向和步长默认正向。 方向&#xff1a; 1 表示从左向右 0,1,2,3,4&#xff0c;5。。。 -1 表示从右向左 注意数值的顺序&#xff1a;[5:0]正向不行&#xff0c;反向行 [0:5]正向…

25. Python 字符串的切片方法

25. Python 字符串的切片方法 文章目录 25. Python 字符串的切片方法1. 索引取值知识回顾2. 什么是切片3. 切片的语法4. 切片示例4.1 步长为1的切片取值4.2 步长为2的切片取值4.3 省略开始索引4.4 省略结束索引4.5 步长为-2 5. 课堂练习6. 总结 1. 索引取值知识回顾 【索引取值…

Go语言切片详解

切片&#xff08;slice&#xff09;是对数组的一个连续片段的引用&#xff0c;所以切片是一个引用类型&#xff08;因此更类似于 C/C 中的数组类型&#xff0c;或者 Python 中的 list 类型&#xff09;&#xff0c;这个片段可以是整个数组&#xff0c;也可以是由起始和终止索引…

字符串的切片1

切片的基本语法格式&#xff1a;[头下标&#xff1a;尾下标&#xff1a;步长] 1.字符串切片可以对字符串进行截取操作&#xff0c;获取一段子串。 2.[头下标&#xff1a;尾下标]遵循前闭后开规则&#xff08;头标可取到&#xff0c;尾标取不到&#xff09;。 3.步长可省略&a…

Python3的切片

Python3的切片非常灵活&#xff0c;可以很方便地对有序序列进行切片操作&#xff0c;代码简单易用。 大家都知道&#xff0c;我们可以直接使用索引来访问序列中的元素&#xff0c;同时索引可分为正向和负向两种&#xff0c;而切片也会用到索引&#xff0c;下面放上一个图&…

Python列表切片详解([][:][::])

Python切片是list的一项基本的功能&#xff0c;最近看到了一个程序&#xff0c;里面有这样一句类似的代码&#xff1a; a list[::10] 不太明白两个冒号的意思就上网百度&#xff0c;发现大多数人写的博客中都没有提到这一个用法&#xff0c;因此自己翻阅《Python核心编程中文…

Numpy 数组切片

一、列表切片&#xff08;一维数组&#xff09; 1.1、切片原理 列表切片是从原始列表中提取列表的一部分的过程。在列表切片中&#xff0c;我们将根据所需内容&#xff08;如&#xff0c;从何处开始&#xff0c;结束以及增量进行切片&#xff09;剪切列表。Python中符合序列的…

python 字符串切片

1. 字符串的索引 字符串的索引从前往后是从0开始计数&#xff0c;从后往前是从-1开始依次 -1 2.字符串切片方法 语法格式 str[beginIndex:endIndex:step]取值结果: [begin,end) / 含头不含尾 步长不设置时默认为1 3.切片 ① 取x-y位置的字符串: 从中间开始&#xff0c;中间…