phontomjs webPage模块方法

2024-05-07 02:08

本文主要是介绍phontomjs webPage模块方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

随时随地技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(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');

这篇关于phontomjs webPage模块方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/966032

相关文章

python: 多模块(.py)中全局变量的导入

文章目录 global关键字可变类型和不可变类型数据的内存地址单模块(单个py文件)的全局变量示例总结 多模块(多个py文件)的全局变量from x import x导入全局变量示例 import x导入全局变量示例 总结 global关键字 global 的作用范围是模块(.py)级别: 当你在一个模块(文件)中使用 global 声明变量时,这个变量只在该模块的全局命名空

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

浅谈主机加固,六种有效的主机加固方法

在数字化时代,数据的价值不言而喻,但随之而来的安全威胁也日益严峻。从勒索病毒到内部泄露,企业的数据安全面临着前所未有的挑战。为了应对这些挑战,一种全新的主机加固解决方案应运而生。 MCK主机加固解决方案,采用先进的安全容器中间件技术,构建起一套内核级的纵深立体防护体系。这一体系突破了传统安全防护的局限,即使在管理员权限被恶意利用的情况下,也能确保服务器的安全稳定运行。 普适主机加固措施:

webm怎么转换成mp4?这几种方法超多人在用!

webm怎么转换成mp4?WebM作为一种新兴的视频编码格式,近年来逐渐进入大众视野,其背后承载着诸多优势,但同时也伴随着不容忽视的局限性,首要挑战在于其兼容性边界,尽管WebM已广泛适应于众多网站与软件平台,但在特定应用环境或老旧设备上,其兼容难题依旧凸显,为用户体验带来不便,再者,WebM格式的非普适性也体现在编辑流程上,由于它并非行业内的通用标准,编辑过程中可能会遭遇格式不兼容的障碍,导致操

透彻!驯服大型语言模型(LLMs)的五种方法,及具体方法选择思路

引言 随着时间的发展,大型语言模型不再停留在演示阶段而是逐步面向生产系统的应用,随着人们期望的不断增加,目标也发生了巨大的变化。在短短的几个月的时间里,人们对大模型的认识已经从对其zero-shot能力感到惊讶,转变为考虑改进模型质量、提高模型可用性。 「大语言模型(LLMs)其实就是利用高容量的模型架构(例如Transformer)对海量的、多种多样的数据分布进行建模得到,它包含了大量的先验

【北交大信息所AI-Max2】使用方法

BJTU信息所集群AI_MAX2使用方法 使用的前提是预约到相应的算力卡,拥有登录权限的账号密码,一般为导师组共用一个。 有浏览器、ssh工具就可以。 1.新建集群Terminal 浏览器登陆10.126.62.75 (如果是1集群把75改成66) 交互式开发 执行器选Terminal 密码随便设一个(需记住) 工作空间:私有数据、全部文件 加速器选GeForce_RTX_2080_Ti

【VUE】跨域问题的概念,以及解决方法。

目录 1.跨域概念 2.解决方法 2.1 配置网络请求代理 2.2 使用@CrossOrigin 注解 2.3 通过配置文件实现跨域 2.4 添加 CorsWebFilter 来解决跨域问题 1.跨域概念 跨域问题是由于浏览器实施了同源策略,该策略要求请求的域名、协议和端口必须与提供资源的服务相同。如果不相同,则需要服务器显式地允许这种跨域请求。一般在springbo

AI(文生语音)-TTS 技术线路探索学习:从拼接式参数化方法到Tacotron端到端输出

AI(文生语音)-TTS 技术线路探索学习:从拼接式参数化方法到Tacotron端到端输出 在数字化时代,文本到语音(Text-to-Speech, TTS)技术已成为人机交互的关键桥梁,无论是为视障人士提供辅助阅读,还是为智能助手注入声音的灵魂,TTS 技术都扮演着至关重要的角色。从最初的拼接式方法到参数化技术,再到现今的深度学习解决方案,TTS 技术经历了一段长足的进步。这篇文章将带您穿越时

模版方法模式template method

学习笔记,原文链接 https://refactoringguru.cn/design-patterns/template-method 超类中定义了一个算法的框架, 允许子类在不修改结构的情况下重写算法的特定步骤。 上层接口有默认实现的方法和子类需要自己实现的方法