How do I access an iframe from CasperJS?

后端 未结 5 1747
情书的邮戳
情书的邮戳 2020-11-29 04:33

I have a webpage with an iframe. I\'d like to access the contents of the iframe using CasperJS. In particular, I need to click buttons and fill a form. How can I do that?

相关标签:
5条回答
  • 2020-11-29 04:57

    As a matter of fact you'll have to use the new --web-security=no feature provided by Phantomjs 1.5 in order to be able to access those iFrames and their contents.

    0 讨论(0)
  • 2020-11-29 05:00

    Suppose we have different frames(frame1 and frame2) and we have to access different elements(like click or check if div tag exits or not) of those frames.

    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");
                }
          );
       });
    });
    
    0 讨论(0)
  • 2020-11-29 05:20

    You can do something like this:

    casper.start("url here...", function() { 
        this.withFrame(0, function() {
            this.evaluate(function() {
                document.querySelector('img#btn_start').click();
            })
        })
    });
    

    You can replace the zero with the name of the iframe.

    0 讨论(0)
  • 2020-11-29 05:21

    Spent forever looking for this, and of course I found the answer minutes after posting the question.

    I can use the new frame switching commands added to phantomjs in this commit. Specifically, the this.page.switchToChildFrame(0) and this.page.switchToParentFrame() functions. It appears undocumented, and it also seems that the methods have been changed for upcoming releases, but it does work:

    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();
    });
    
    0 讨论(0)
  • 2020-11-29 05:22

    From 1.0 you can use withFrame

      casper.open("http://www.example.com/page.html", function() {
        casper.withFrame('flashHolder', function() {
          this.test.assertSelectorExists('#the-flash-thing', 'Should show Flash');
        });
      });
    
    0 讨论(0)
提交回复
热议问题