0

在我的一项任务中,我必须制作一个纯粹使用 JavaScript 的网络爬虫。这意味着,输入将是一个 URL,输出将是从该页面开始的所有链接的树。我使用了使用 YQL的插件https://github.com/padolsey/jQuery-Plugins/tree/master/cross-domain-ajax/ ,它可以获取网站上的所有链接。(就像我为 Google 的主页所做的那样,http://deepakpathak.in/langoor/linkfinder.html)。但是,我无法从中制作树形结构。有没有其他更简单的方法来制作给定网站的链接树,并且在 Javascript 中?

4

1 回答 1

1

你没有提到你想做什么样的树,输出应该是某种网站上的树列表组件还是你想把它放在数据库中?

但是,您可以使用普通的旧 javascript 对象和数组来创建(查找树数据结构上的任何注释以了解它们是如何工作的,有很多方法可以表示它们)。为了让你开始,一个基本的树看起来像这样(带有一个createNode函数):

var createNode = function(content) {
    return {
        'nodes': [], // children are put here
        'content': content // puts the content here
    };
};

var treeroot = createNode();
    // create the root node of the tree
    // content is undefined

treeroot.nodes.push(createNode(myTreeNode)); 
    // accesses the nodes array and pushes a new node into the root node
    // content in that node will be whatever "myTreeNode" is

您必须自己编写遍历算法,因为 javascript 没有任何函数来处理树。或者使用 DOM 本身创建树(因为它是树数据结构)。

于 2012-04-13T10:33:33.177 回答