网页';s使用Phantom的HTML


Webpage's HTML using Phantom

我正在尝试使用PhantomJS加载页面(使用Javascript加载网页上的项目),并将页面上的所有HTML(至少在<body />标记内)返回给执行phantomjs httpget.js的PHP函数。

问题:我可以让phantomjs返回document.title,但简单地要求它返回console.log(document.body)会给我一个[object Object]。如何提取页面的HTML?

与浏览器相比,使用phantomjs加载网页也需要更长的时间

httpget.js

console.log('hello!');
var page = require('webpage').create();
page.open("http://www.asos.com/Men/T-Shirts-Vests/Cat/pgecategory.aspx?cid=7616#parentID=-1&pge=0&pgeSize=900&sort=1",
    function(status){
        console.log('Page title is ' + page.evaluate(function () {
            return document.body;
        }));
        phantom.exit();
    });

输出(从shell运行)

hello!
Page title is [object Object]

document.body.innerHTML包含正文的HTML。

不确定这与Node.js有什么关系,因为您似乎直接使用PhantomJS,而不是节点(或通过节点phantom使用phantom)。。。

但要回答你的问题,你需要这样做:

var html = page.evaluate(function () {
    var root = document.getElementsByTagName("html")[0];
    var html = root ? root.outerHTML : document.body.innerHTML;
    return html
});

这适用于没有外部<html>标签。

阅读文档,page.content将获得整个HTML。