如何使用Phantomjs获取URI

时间:2013-11-25 10:23:35

标签: c# wpf phantomjs

我需要获取网站(所有链接)中所有网页的列表。我必须使用Phantomjs,但我以前从未使用它。任何人都可以解释我,我怎么能用它?如何在Phantomjs的帮助下解析html代码以获取所有链接?

1 个答案:

答案 0 :(得分:1)

PhantomJS是一个带有JavaScript API的无头WebKit脚本。它被重新编译为单个可执行文件。

有适用于Windows的正式版本,Mac ou Linux,但如果需要,您也可以构建自己的版本。

  • 创建脚本

PhantomJS本身没有任何作用,它只是一个可执行文件。您必须编写/编写您的操作脚本。这是通过javascript或Coffee Script完成的。​​

  • 运行脚本

从命令提示符类型,您只需编写

> phantomjs yourscript.js

有时候,你必须为phantomjs创建一个包装器。特别是在WPF中,使用Process / ProcessStartInfo类来管理脚本执行。

  • 如何编写脚本?

如果您熟悉Javascript,尤其是Node.js开发,那么学习曲线很小。 quick start可能是宝贵的,并且毫不犹豫地用available examples来练习自己。这是最困难的部分,但经过几个脚本后会更容易。

要回答您的初步问题,这是一个可能的脚本

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

if (system.args.length != 2) {
    console.log('Usage: so20189669.js <URL> ');
    phantom.exit(1);
} else {
    var url = system.args[1]; 
    page.open(url, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
            phantom.exit();
        } else {
            var links = page.evaluate(function () {
                return [].map.call(document.querySelectorAll('a'), function (link) { return link.getAttribute('href') });
            });

            console.log(JSON.stringify(links));
            phantom.exit();
        }
    });
}

在命令提示符中:

>phantomjs.exe so20189669.js http://stackoverflow.com/questions/20189669/how-to-get-uri-with-phantomjs

没有神奇的答案,你必须根据自己的需要改变它!