Как получить доступ к iframe из CasperJS?
У меня есть веб-страница с iframe. Я хотел бы получить доступ к содержимому iframe, используя CasperJS. В частности, мне нужно нажать кнопки и заполнить форму. Как я могу это сделать?
Основная веб-страница
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>
IFrame:
<html><body>
<a id='iframe-c' href="javascript:console.log('pressed iframe-c');">iframe-c</a>
</body></html>
Мой наивный подход:
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();
});
Не работает, конечно, потому что селектор 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] [phantom] Navigation requested: url=http://jim.sh/~jim/tmp/casper/iframe.html, type=Other, lock=true, isMainFrame=false
[debug] [phantom] Successfully injected Casper client-side utilities
[info] [phantom] Step 2/2 http://jim.sh/~jim/tmp/casper/main.html (HTTP 200)
[debug] [phantom] Mouse event 'click' on selector: a#main-a
[info] [remote] pressed main-a
[debug] [phantom] Mouse event 'click' on selector: a#main-b
[info] [remote] pressed main-b
[debug] [phantom] Mouse event 'click' on selector: a#iframe-c
FAIL CasperError: Cannot dispatch click event on nonexistent selector: a#iframe-c
# type: uncaughtError
# error: "CasperError: Cannot dispatch click event on nonexistent selector: a#iframe-c"
CasperError: Cannot dispatch click event on nonexistent selector: a#iframe-c
/tmp:901 in mouseEvent
/tmp:365 in click
/tmp/test.js:9
/tmp:1103 in runStep
/tmp:324 in checkStep
Есть ли способ сделать эту работу? Взлом, который включает в себя выкрикивание в phantomjs напрямую, будет прекрасным, но я не знаю, что делать там.
Я использую CasperJS версии 1.0.0-RC1 и phantomjs версии 1.6.0.
Ответы
Ответ 1
Провел навсегда поиск этого, и, конечно же, я нашел ответы на несколько минут после публикации вопроса.
Я могу использовать новые команды переключения кадров, добавленные в phantomjs в этот коммит. В частности, функции this.page.switchToChildFrame(0)
и this.page.switchToParentFrame()
. Он кажется недокументированным, и также кажется, что методы были изменены для будущих выпусков, но он работает:
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.page.switchToChildFrame(0);
this.click('a#iframe-c');
this.page.switchToParentFrame();
});
casper.run(function() {
this.exit();
});
Ответ 2
Из 1.0 вы можете использовать withFrame
casper.open("http://www.example.com/page.html", function() {
casper.withFrame('flashHolder', function() {
this.test.assertSelectorExists('#the-flash-thing', 'Should show Flash');
});
});
Ответ 3
На самом деле вам придется использовать новый --web-security=no
функция, предоставляемая Phantomjs 1.5
, чтобы иметь доступ к этим
iFrames
и их содержимое.
Ответ 4
Предположим, что у нас есть разные кадры (frame1 и frame2), и нам нужно получить доступ к различным элементам (например, щелкнуть или проверить, выходит ли тег div из этих фреймов).
casper.withFrame('frame1', function() {
var file = '//*[@id="profile_file"]';
casper.thenClick(x(file));
});
casper.withFrame('frame2', function() {
casper.then(function () {
casper.waitForSelector('#pageDIV',
function pass() {
console.log("pass");
},
function fail(){
console.log("fail");
}
);
});
});