小编Jim*_*ris的帖子

如何从CasperJS访问iframe?

我有一个带iframe的网页.我想使用CasperJS访问iframe的内容.特别是,我需要单击按钮并填写表单.我怎样才能做到这一点?

主要网页是 main.html:

<html><body>
<a id='main-a' href="javascript:console.log('pressed main-a');">main-a</a>
<iframe src="iframe.html"></iframe>
<a id='main-b' href="javascript:console.log('pressed main-b');">main-b</a>
</body></html>
Run Code Online (Sandbox Code Playgroud)

iframe是:

<html><body>
<a id='iframe-c' href="javascript:console.log('pressed iframe-c');">iframe-c</a>
</body></html>
Run Code Online (Sandbox Code Playgroud)

我天真的做法:

var casper = require('casper').create({
    verbose: true,
    logLevel: "debug"
});

casper.start("http://jim.sh/~jim/tmp/casper/main.html", function() {
    this.click('a#main-a');
    this.click('a#main-b');
    this.click('a#iframe-c');
});

casper.run(function() {
    this.exit();
});
Run Code Online (Sandbox Code Playgroud)

当然,这不起作用,因为a#iframe-c选择器在主框架中无效:

[info] [phantom] Starting...
[info] [phantom] Running suite: 2 steps
[debug] [phantom] opening url: http://jim.sh/~jim/tmp/casper/main.html, HTTP GET
[debug] [phantom] Navigation requested: url=http://jim.sh/~jim/tmp/casper/main.html, type=Other, lock=true, isMainFrame=true
[debug] [phantom] url changed to "http://jim.sh/~jim/tmp/casper/main.html"
[debug] …
Run Code Online (Sandbox Code Playgroud)

javascript iframe webkit phantomjs casperjs

32
推荐指数
2
解决办法
2万
查看次数

标签 统计

casperjs ×1

iframe ×1

javascript ×1

phantomjs ×1

webkit ×1