从手动jQuery代码创建蜘蛛的最简单方法?

时间:2013-07-26 12:01:43

标签: jquery web-crawler mechanize casperjs

我有一个最好被描述为jQuery“脚本”:

//  Get the Textbooks URL
window.location = $($("li.dropDown").find("a")[0]).attr('href');

//  Fill in Department Data
var depts = $($(".deptSelectInput")[0]).next().children();
$($(".deptSelectInput")[0]).val($($(".deptSelectInput")[0]).next().children().text());
$($(".deptSelectInput")[0]).blur();

//  Fill in Course Data
var courses = $($(".courseSelectInput")[0]).next().children();
$($(".courseSelectInput")[0]).val($($(".courseSelectInput")[0]).next().children().text());
$($(".courseSelectInput")[0]).blur();

//  Fill in Section Data
var sections = $($(".sectionSelectInput")[0]).next().children();
$($(".sectionSelectInput")[0]).val($($(".sectionSelectInput")[0]).next().children().text())
$($(".sectionSelectInput")[0]).blur();


//  Submit the form, only if it's valid
if (($(".noTextBookCourseErrorMessage")[0].style.display) == "none") {
    formSubmission();
}


//  Extract all the ISBNs from the page
var regex = /\d+/g;
var isbn = $('li:contains("ISBN")').text().trim();
var isbns = [];

var tempIsbn = regex.exec(isbn);
while (tempIsbn) {
    isbns.push(parseInt(tempIsbn[0], 10));
    tempIsbn = regex.exec(isbn);
}

console.log(isbns);

它完全符合我的需要。

当我在Chrome中打开开发工具并分三次发布此脚本时(一次加载新网址,一次获取数据并提交表单,一次从新页面读取),它将返回给我我想要的数据。

我对蜘蛛很新,并且想知道自动化这个过程的最佳方法是什么。基本上,我需要一个我可以运行的脚本,它将完成我刚才所做的事情(分解三个jQuery帖子)。

我已经研究过CasperJS并进行机械化,但从未使用过。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

在您的情况下,您尝试抓取的Web上下文包含通过JQuery的动态内容,如果您想使用Javascript来实现这一点,CasperJS是一个很好的选择。您可以使用它来触发事件,添加流程步骤,包括在每个ajax调用之后等待和验证的函数,然后再处理任何下一步。

这是一个如何使用CasperJS和JQuery抓取网站的示例 CasperJs and Jquery with chained Selects

对于来自CasperJS的执行javascript代码,您必须使用evaluate()方法

  

evaluate()方法作为CasperJS环境与您打开的页面之间的门;每当你将一个闭包传递给evaluate()时,你就像进入浏览器控制台一样进入页面并执行代码。