在树中存储站点的链接

时间:2010-09-07 12:27:18

标签: algorithm tree

我正在尝试存储我从非二叉树中的网站上抓取的链接。链接按层次布局(显然)。问题是如何生成树?我的意思是,我如何通过链接提供的页面工作,以便我知道谁是谁的孩子。

现在我可以获得第一级和第二级链接,但不知道如何从这里开始除了我必须递归地构建它并且有一种方法可以在我到达叶子时停止(其中我有)。

我在想的是(Python中的代码):

def buildTree(root):
for node in root.children:
    if <end condition here>:
        continue
    else:
        nodes = getNodes(urllib2.urlopen(node.url).read())
        node.addChildren(nodes)
        buildTree(node)

其中根和节点是用户定义的节点

1 个答案:

答案 0 :(得分:1)

显然,网站中的链接不是树,而是。你应该有一个由URL标识的Page对象和一个从一个页面指向另一个页面的链接对象(而页面A可以指向页面B,而页面B指向页面A,使其成为图形,而不是树)。

扫描算法伪代码:

process_page(current_page):
    for each link on the current_page: 
    if target_page is not already in your graph:
        create a Page object to represent target_page
        add it to to_be_scanned set
    add a link from current_page to target_page

scan_website(start_page)
    create Page object for start_page
    to_be_scanned = set(start_page)
    while to_be_scanned is not empty:
        current_page = to_be_scanned.pop()
        process_page(current_page)