我受困于 CasperJS 脚本:
var casper = require('casper').create();
var fs=require('fs');
casper.start('http://int.soccerway.com/national/switzerland/super-league/20152016/regular-season/r31601/matches/?ICID=PL_3N_02', function() {
this.wait(2000, function() {
fs.write("swiss.html", this.getHTML() );
});
this.wait(2000, function() {
var evObj = document.createEvent('Events');
evObj.initEvent('click', true, false);
document.getElementById('page_competition_1_block_competition_matches_6_previous').dispatchEvent(evObj);
});
this.wait(2000, function() {
fs.write("swiss2.html", this.getHTML() );
});
});
casper.run();
我想在代码中打开链接,而不是单击上一步并获取页面的 html(我想获取包含每场比赛结果的整个赛季的 html 文档)。
我做错了什么? (我是首发)
谢谢你..
最佳答案
脚本几乎是正确的。唯一的错误是在与页面交互时(单击“上一个”按钮)。
您无法从脚本内部访问页面元素,您必须在打开的网页上下文中评估(“注入(inject)”)该代码。在 CasperJS 中,有 casper.evaluate()功能来做到这一点。
var casper = require('casper').create();
var fs=require('fs');
casper.start('http://int.soccerway.com/national/switzerland/super-league/20152016/regular-season/r31601/matches/?ICID=PL_3N_02', function() {
this.wait(2000, function() {
fs.write("swiss.html", this.getHTML() );
});
this.wait(2000, function() {
// Code inside of this function will run
// as if it was placed inside the target page.
casper.evaluate(function(term) {
var evObj = document.createEvent('Events');
evObj.initEvent('click', true, false);
var prev_link = document.getElementById('page_competition_1_block_competition_matches_6_previous');
prev_link.dispatchEvent(evObj);
});
});
this.wait(2000, function() {
fs.write("swiss2.html", this.getHTML() );
});
});
casper.run();
或者,不用 casper.evaluate,你可以简单地写
this.click('#page_competition_1_block_competition_matches_6_previous');
正如 Artjom B. 建议的那样。
关于javascript - PhantomJS 和 CasperJS 单击链接并获取 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33808693/