[英]CasperJS: How do you click on all selected buttons?
I'm trying to use CasperJS as a web scraper, and there's a page with buttons that will load data when clicked. 我正在尝试使用CasperJS作为网络抓取工具,并且有一个页面包含按钮,点击时会加载数据。 So, I'd like to click all of these buttons first and wait before actually making a query to grab all the necessary data.
所以,我想首先点击所有这些按钮,然后在实际进行查询之前等待以获取所有必要的数据。
The problem is that with Casper, casper.thenClick(selector)
clicks the first element. 问题是,使用Casper,
casper.thenClick(selector)
单击第一个元素。 But how do you iterate and click each element based on the selector? 但是,如何基于选择器迭代并单击每个元素?
Note that these buttons do not have ids. 请注意,这些按钮没有ID。 They all have generic class selectors.
它们都有通用的类选择器。
Ex. 防爆。
<h3>
<span>Text 1</span>
<span>
<button class="load-btn">show</button>
</span>
</h3>
<h3>
<span>Text 2</span>
<span>
<button class="load-btn">show</button>
</span>
</h3>
<h3>
<span>Text 3</span>
<span>
<button class="load-btn">show</button>
</span>
</h3>
And for some reason casper.thenClick("h3:contains('text 1') .load-btn")
doesn't work. 由于某种原因,
casper.thenClick("h3:contains('text 1') .load-btn")
不起作用。
I created a new 'click' function, you can click on each element by using for
cycle: 我创建了一个新的“点击”功能,您可以使用
for
循环点击每个元素:
function click(sel){var event=document.createEvent('MouseEvents');event.initMouseEvent('click',1,1,window,1,0,0,0,0,0,0,0,0,0,null);sel.dispatchEvent(event);}
var casper = require('casper').create({
verbose: true,
logLevel: 'debug',
waitTimeout: 5000,
userAgent: 'Mozilla/5.0 (X11; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0',
viewportSize:{width: 1600, height: 900}
});
casper
.on("error", function(msg){ this.echo("error: " + msg, "ERROR") })
.on("page.error", function(msg, trace){ this.echo("Page Error: " + msg, "ERROR") })
.on("remote.message", function(msg){ this.echo("Info: " + msg, "INFO") })
.start("http://domu-test-2/node/12", function(){
this.evaluate(function(click){
var i, x = document.querySelectorAll("button.load-btn");
for(i = 0; i < x.length; i++) {
click(x[i]);
} //'click' for each element
}, click);
})
.run();
With this HTML: 使用此HTML:
<h3>
<span>Text 1</span>
<span>
<button class="load-btn" onclick='console.log("1")'>show</button>
</span>
</h3>
<h3>
<span>Text 2</span>
<span>
<button class="load-btn" onclick='console.log("2")'>show</button>
</span>
</h3>
<h3>
<span>Text 3</span>
<span>
<button class="load-btn" onclick='console.log("3")'>show</button>
</span>
</h3>
Will print: 将打印:
Info: 1
Info: 2
Info: 3
In green color. 绿色。
You could try dropping into the DOM using evaluate instead (I assume the page has jquery on it). 您可以尝试使用evaluate替换为DOM(我假设页面上有jquery)。
casper.thenEvaluate(function() {
$('button.load-btn').click();
});
Remember that you will need to WAIT for something to appear afterwards. 请记住,您需要等待事后出现的内容。
casper.wait(2000, function() {...});
or using one of the waitFor function 或者使用waitFor函数之一
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.