Python遍历图数据库存储的DOM树 递归生成HTML文件的实现问题
解决方案
核心修改逻辑
- 给
graph_dom递归函数新增第二个参数:当前节点需要挂载的父BeautifulSoup标签对象,避免所有节点都直接挂载到soup根节点 - 遍历当前节点的子节点时,在创建完子标签后直接触发递归,传入子节点ID和刚创建的子标签作为下一层的挂载容器,完成深度优先遍历
修正后代码
from bs4 import BeautifulSoup # 初始化soup,根据你的实际需求指定解析器即可 soup = BeautifulSoup(features="html.parser") cursor = ag.execCypher("MATCH (n:node {tag: 'html'}) RETURN n") t = [x[0].id for x in cursor] print(t[0]) # 新增第二个参数parent_element:当前节点要挂载到的父标签 def graph_dom(t_id, parent_element): parent = ag.execCypher("MATCH (n:node) WHERE id(n) = %s RETURN n", params=(t_id,)) p = [x[0] for x in parent] pt = p[0]["tag"] pid = p[0].id print(f"|> parent Id: {pid} --- parent tag {pt}") current_tag = soup.new_tag(name=p[0]["tag"]) # 把当前节点挂到传入的父标签上,而非直接挂到soup根节点 parent_element.append(current_tag) children = ag.execCypher("MATCH (v:node)-[R:connect]->(V2) WHERE id(v) = %s RETURN V2", params=(p[0].id,)) for d in children: children_tag = soup.new_tag(name=d[0]["tag"]) current_tag.append(children_tag) dt = d[0]["tag"] did = d[0].id print(f"child id {did} child tag: {dt}") # 递归调用,传入子节点id和刚创建的子标签作为下一层的挂载容器 graph_dom(did, children_tag) # 根节点调用时,父挂载容器为soup本身 graph_dom(t[0], soup) file_soup = soup.prettify() with open("helloworld.html", "w") as file: file.write(str(file_soup))
效果验证
修改后递归会自动遍历所有层级的节点,按照图数据库存储的父子关系生成嵌套的HTML结构,你示例的DOM树会完整生成包含title、ul、li的完整代码。
内容的提问来源于stack exchange,提问作者alexander
相关产品推荐
相关产品推荐

