PhantomJS and iFrame

2020-05-27 03:29发布

I'm using phantomjs(1.5) and casperjs for my functional tests.

casper = require('casper').create
  loadImages: false


casper.start 'http://vk.com', ->
  @fill 'form[name="login"]', { email: mail, pass: pass}, true

casper.thenOpen "http://vk.com/#{app}", ->
  @echo "User at #{app}"  
casper.then ->
  @click "iframe['element']" #?! how I can do it?
casper.then ->
  @wait 2000000, -> @echo "exit from room: #{num}"


casper.run()

So, I login to vk.com (social network in Russia), my app loaded with iframe.

How I can use elements in iFrame, for example click to a button?

2条回答
Deceive 欺骗
2楼-- · 2020-05-27 04:16

The recent versions of PhantomJS allow us to use the --web-security=no flag for non respect the security policy.

The next script (only PhantomJS) get the title of a link in the iframe, an iframe (adsense).

/*
    Accessing an iframe (different domain) with PhantomJS
    Example by deerme.org
*/

var page = require('webpage').create(), system = require('system'), t, address;
if (system.args.length === 1)
{
    console.log('Usage: phantomfs iframe.js <some URL>');
    phantom.exit();
}

t = Date.now();
address = system.args[1];
page.open(address, function (status)
{
    if (status !== 'success')
    {
            console.log('FAIL to load the address');
    }
    else
    {
        t = (Date.now()) - t;
        title = page.evaluate( function(){
            return document.title;
        });
        linkTitle = page.evaluate( function(){
            // The site containing jQuery?
            if ( typeof(jQuery) == "undefined" )
            {
                // Force Load
                page.injectJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
            }
            // first iframe #aswift_2
            // second iframe #google_ads_frame3
            return jQuery("#aswift_2").contents()
                .find("body")
                    .find("#google_ads_frame3")
                        .contents()
                            .find("body")
                                .contents()
                                    .find("a:last")
                                        .attr("title");
        });
        console.log('Loading time: ' + t + ' msec');    
        console.log('Webpage title: ' + title);
        console.log('Link title (iframe adsense): ' + linkTitle);
    }
    phantom.exit();
});

Remember, run with the parameter

phantomjs --web-security=no iframe.js http://anysite.org

查看更多
够拽才男人
3楼-- · 2020-05-27 04:18

If your application is on a different domain than the one in the iframe, then your script can't interact with the iframe's contents. See: Can scripts in iframe interact with scripts in the main page

查看更多
登录 后发表回答