Python通过PhantomJS获取JS渲染后的网页源代码

新建一个文件,命名为test.js,内容如下:

var page = require('webpage').create(),
system = require('system'),
address;

if (system.args.length === 1) {
    phantom.exit(1);
} else {
    address = system.args[1];
    page.open(address, function(status) {
        if (status !== 'success') {
            phantom.exit();
        } else {
            var sc = page.evaluate(function() {
                return document.body.innerHTML;
            });
            window.setTimeout(function() {
                console.log(sc);
                phantom.exit();
            }, 1000);
        }
    });
};

新建一个文件,命名为test.py,内容如下:

# -*- coding: utf-8 -*-
import subprocess

def get_html(url):
    cmd = 'phantomjs test.js "%s"' % url
    stdout, stderr = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    print stderr
    print stdout

if __name__ == '__main__':  
    url = 'https://mm.taobao.com/self/model_card.htm?user_id=687471686'
    get_html(url)

执行下列命令:

python test.py

如果你能看到源代码,就表示没问题了。执行速度可能有点慢,请耐心等待。

原文地址:https://www.cnblogs.com/yestreenstars/p/5511544.html