4

我想使用纯 phantom.js 代码切换到 iframe

这是我的第一次尝试

var page = new WebPage();
var url = 'http://www.theurltofectch'
page.open(url, function (status) {
    if ('success' !== status) {
        console.log("Error");
    } else {
        page.switchToFrame("thenameoftheiframe");
        console.log(page.content);
        phantom.exit();
    }
});

它只生成主页的源代码。任何想法 ?

请注意,iframe 域与主页域不同。

4

3 回答 3

2

代替

console.log(page.content);

console.log(page.frameContent);

应该返回 phantomjs 切换到的框架的内容。

如果 iframe 来自另一个域,您可能需要添加 --web-security=no 选项,如下所示:

phantomjs --web-security=no myscript.js

作为附加信息,xMythicx 所说的可能是真的。页面加载完成后,一些 iframe 会通过 Javascript 呈现。如果 iframe 内容为空,则需要等待所有资源完成加载,然后才能开始从页面中抓取内容。但这是另一个问题,如果你需要这个问题的答案,我建议你问一个关于它的新问题,我会在那里回答。

于 2014-02-12T03:21:54.170 回答
2

请试一试,我相信这可能是一个异步问题,这意味着在尝试访问它时 iframe 不存在。我从另一篇文章中收到了以下片段。

var page = require('webpage').create(),
    testindex = 0,
    loadInProgress = false;

page.onConsoleMessage = function(msg) {
  console.log(msg);
};

page.onLoadStarted = function() {
  loadInProgress = true;
  console.log("load started");
};

page.onLoadFinished = function() {
  loadInProgress = false;
  console.log("load finished");
};

/*
page.onNavigationRequested = function(url, type, willNavigate, main) {
  console.log('Trying to navigate to: ' + url);
  console.log('Caused by: ' + type);
  console.log('Will actually navigate: ' + willNavigate);
  console.log('Sent from the page\'s main frame: ' + main);
};
*/


/*
  The steps array represents a finite set of steps in order to perform the unit test
*/

var steps = [
  function() {
    //Load Login Page
    page.open("https://www.yourpage.com");
  },
  function() {
    //access your iframe here
    page.evaluate(function() {


    });
  }, 
  function() {
   //any other step you want 
    page.evaluate(function() {



    });
  }, 
  function() {
    // Output content of page to stdout after form has been submitted
    page.evaluate(function() {
      //console.log(document.querySelectorAll('html')[0].outerHTML);
    });

    //render a test image to see if login passed
    page.render('test.png');

  }
];


interval = setInterval(function() {
  if (!loadInProgress && typeof steps[testindex] === "function") {
    console.log("step " + (testindex + 1));
    steps[testindex]();
    testindex++;
  }
  if (typeof steps[testindex] !== "function") {
    console.log("test complete!");
    phantom.exit();
  }
}, 50);
于 2014-01-31T16:13:39.350 回答
1

对 iframe 有同样的问题,并且

phantomjs --web-security=no

对我有帮助:]

于 2015-09-26T04:17:48.203 回答