简体   繁体   English

如何使用CasperJS解析网站上的iframe

[英]How to parse iframe on a website with CasperJS

I want obtain informations on a website with iframe. 我想在iframe网站上获取信息。

When I parse this website with casperjs with this command : 当我使用以下命令使用casperjs解析此网站时:

casper.then(function() {
    casper.waitFor(function() {
        return this.withFrame('mainframe', function() {});
    }, function() {
        this.withFrame('mainframe', function() {
            console.log(this.echo(this.getHTML()));
        });
    });
}); 

My problem is the result, I have content of one iframe only. 我的问题是结果,我只有一个iframe的内容。

How I can obtain a result of any iframe present on my website? 如何获得网站上存在的所有iframe的结果?

CasperJS doesn't specifically provide a function to wait for an iframe to load. CasperJS没有专门提供等待iframe加载的功能。 However, you can use the waitForResource() step function to wait for the iframe resource and then act on it. 但是,您可以使用waitForResource()步骤功能来等待iframe资源,然后对其进行操作。

casper.waitForResource(function check(res){
    var iframeSrc = this.getElementAttribute("iframe[name='mainframe']", "src");
    return res.url.indexOf(iframeSrc) > -1;
}, function(){
    // success
});

When the resource is received, then you can wait inside of the iframe for a specific selector in order to continue with your script as soon as the iframe is fully loaded: 收到资源后,您可以在iframe中等待特定的选择器,以便在iframe完全加载后继续执行脚本:

casper.waitForResource(function check(res){
    var iframeSrc = this.getElementAttribute("iframe[name='mainframe']", "src");
    return res.url.indexOf(iframeSrc) > -1;
}).withFrame('mainframe', function(){
    this.waitForSelector("someSelectorForAnElement thatIsLoadedAtTheEnd", function(){
        this.echo(this.getHTML());
    });
});

casper.waitFor(function() {
    return this.withFrame('mainframe', function() {});
}, function() {

This code doesn't wait at all. 这段代码根本不用等待。 CasperJS supports a Fluent API, so that you can chain multiple step functions together like this: CasperJS支持Fluent API,因此您可以将多个步骤函数链接在一起,如下所示:

casper.start(url)
    .then(function(){...})
    .wait(3000)
    .then(function(){...})
    .run();

This means that the result of withFrame() is the casper object which is evaluated to true for that check function. 这意味着结果withFrame()casper其被评价为对象true该检查功能。 There is no waiting going on. 无需等待。


console.log(this.echo(this.getHTML()));

doesn't make sense, because casper.echo() already prints to the console. 没有任何意义,因为casper.echo()已打印到控制台。 Use either 使用任一

console.log(this.getHTML());

or 要么

this.echo(this.getHTML());

but not both. 但不是两者兼而有之。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM