【问题标题】:How to get the HTML source of a website with PhantomJS如何使用 PhantomJS 获取网站的 HTML 源代码
【发布时间】:2013-12-09 01:10:41
【问题描述】:

下面是一个 PhantomJS 的例子,它通过 DOM id 从外部网页获取一些元素:

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent';
page.open('http://www.httpuseragent.org', function(status) {
  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
    var ua = page.evaluate(function() {
      return document.getElementById('myagent').textContent;
    });
    console.log(ua);
  }
  phantom.exit();
});

我想获取网页的整个 HTML 源代码……我该怎么做?

【问题讨论】:

  • 如果你想要 HTML 源代码,那么使用类似 the http module 的东西,而不是通过浏览器运行页面(它将执行 JS 并用它来破坏 DOM)。

标签: javascript phantomjs


【解决方案1】:

您所要做的就是使用page.content

var page = require('webpage').create();
page.onError = function(msg, trace) {
  //prevent js errors from showing in page.content
  return;
};
page.open('http://www.httpuseragent.org', function () {
    console.log(page.content); //page source
    phantom.exit();
});

【讨论】:

    猜你喜欢
    • 2015-06-17
    • 2017-01-26
    • 2019-01-14
    • 2013-11-20
    • 2012-01-30
    • 2015-12-22
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    相关资源
    最近更新 更多