我正试图将我从一个网站上抓取的链接存储在一个非二叉树中链接是按层次(显然)排列的问题是如何生成树我的意思是,我该如何通过链接提供的页面来了解谁是谁的孩子。
现在我可以得到第一级和第二级的链接,但不知道如何从这里开始,除此之外,我必须递归地构建它,并有一种方法来停止当我得到一片叶子(我有)。
我想的是(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)
其中根和节点是用户定义的节点类
最佳答案
显然,站点中的链接不是树,而是图。您应该有一个由URL标识的Page对象和一个从一个页面指向另一个页面的Link对象(而Page a可以指向Page B,而pageb则指向pagea,使其成为一个图,而不是树)。
扫描算法伪码:
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)
关于algorithm - 将站点的链接存储在树中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3658652/