soo*_*yer 5 javascript jquery web-scraping phantomjs
我是phantomjs,Java脚本和WebScraping的新手.我想要做的是基本的http身份验证,然后访问另一个URL以获取一些信息.这就是我现在所拥有的.请告诉我我做错了什么.
var page = require('webpage').create();
var system = require('system');
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onAlert = function(msg) {
console.log('alert!!>' + msg);
};
page.settings.userName = "foo";
page.settings.password = "bar";
page.open("http://localhost/login", function(status) {
console.log(status);
var retval = page.evaluate(function() {
return "test";
});
console.log(retval);
page.open("http://localhost/ticket/" + system.args[1], function(status) {
if ( status === "success" ) {
page.injectJs("jquery.min.js");
var k = page.evaluate(function () {
var a = $("div.description > h3 + p");
if (a.length == 2) {
console.log(a.slice(-1).text())
}
else {
console.log(a.slice(-2).text())
}
//return document.getElementById('addfiles');
});
}
});
phantom.exit();
});
Run Code Online (Sandbox Code Playgroud)
我正在向这个文件传递一个参数:一个票号,它被附加到第二个URL.
我会高度推荐CasperJS.
CasperJS是一个用Javascript编写的开源导航脚本和测试实用程序,基于PhantomJS--可编写脚本的无头WebKit引擎.它简化了定义完整导航场景的过程,并为执行常见任务提供了有用的高级功能,方法和语法糖,例如:
- 定义和订购浏览导航步骤
- 填写和提交表格
- 点击以下链接
- 捕获页面(或部分页面)的屏幕截图
- 测试远程DOM
- 记录事件
- 下载资源,包括二进制资源
- 编写功能测试套件,将结果保存为JUnit XML
- 抓取网页内容
(来自CasperJS网站)
我最近花了一天时间试图让PhantomJS自己做一些事情,比如填写一个登录表单并导航到下一页.
CasperJS还为表单构建了一个很好的API目的:
http://docs.casperjs.org/en/latest/modules/casper.html#fill
var casper = require('casper').create();
casper.start('http://some.tld/contact.form', function() {
this.fill('form#contact-form', {
'subject': 'I am watching you',
'content': 'So be careful.',
'civility': 'Mr',
'name': 'Chuck Norris',
'email': 'chuck@norris.com',
'cc': true,
'attachment': '/Users/chuck/roundhousekick.doc'
}, true);
});
casper.then(function() {
this.evaluateOrDie(function() {
return /message sent/.test(document.body.innerText);
}, 'sending message failed');
});
casper.run(function() {
this.echo('message sent').exit();
});
Run Code Online (Sandbox Code Playgroud)