您的位置:首页 > 编程语言 > ASP

使用 casperjs 完成百度相关搜索

2017-04-22 20:17 218 查看
百度有一个相关搜索,想借助百度的相关所搜发散一下思维。

你搜索一个关键字的时候,百度会将该关键字的相关内容在页面的最下面展现出来,所以我们可以利用百度的相关搜索进行发散性的扩展

在下面直接给出相关代码,代码有注释,希望能帮助你看懂。

不建议初学者学习!

建议复制之后,明白我所进行的的操作之后,将代码进行更改,完成自己想进行的功能!

完整的例子参见:https://github.com/casperjs/casperjs/blob/master/samples/dynamic.js

//eslint strict:0
//global CasperError, console, phantom, require
phantom.outputEncoding="GBK";

var casper = require("casper").create({
verbose: true ,
clientScripts:  [
'jquery-3.2.1.js'
]
});

// The base links array
// 需要链接的网页
var links = [
"https://www.baidu.com/s?wd=casperjs"
];

// If we don't set a limit, it could go on forever
// 如果不设定一个限定,它会无限制循环下去
var upTo = ~~casper.cli.get(0) || 10;

var currentLink = 0;

// Get the links, and add them to the links array
// 得到一个数组,并将其加入到 links 中
// (It could be done all in one step, but it is intentionally splitted)
function addLinks(link) {
this.then(function() {
var found = this.evaluate(searchLinks);
// this.echo(found.length + " links found on " + link);
links = links.concat(found);
});
}

// Fetch all <a> elements from the page and return
// 获取页面中的 超链接 并将其返回
// the ones which contains a href starting with 'http://'
// 判断 前缀是不是 http:// function searchLinks() {
var words = [];
var tab = $('div.tt').next('table');
$(tab).find('a').each(function(){
words.push('https://www.baidu.com/s?wd=' + $(this).text());
});

return  words;
}

// Just opens the page and prints the title
// 打开页面并打印标题
function start(link) {
this.start(link, function() {
this.echo('Page title: ' + this.getTitle());
});
}

// As long as it has a next link, and is under the maximum limit, will keep running
// 只要下一个链接,并在最大限度下,仍将继续运行
function check() {
if (links[currentLink] && currentLink < 100) {
this.echo('--- Link ' + currentLink + ' ---');
start.call(this, links[currentLink]);
addLinks.call(this, links[currentLink]);
currentLink++;
this.run(check);
} else {
this.echo("All done.");
this.exit();
}
}

casper.start().then(function() {
this.echo("Starting");
});

casper.run(check);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: