【发布时间】:2021-10-05 03:21:39
【问题描述】:
我正在将由 DOM 树构成的分层数据插入到图形数据库中,但是我无法在节点之间建立完整的关系。我在循环时最终截断了树木
下面的代码说明了遍历 DOM 节点、插入标签并获取最后插入的 id。我遇到的问题是如何通过传递从上一次迭代中获得的 ID 来正确连接树。 当我使用递归时,我遇到了同样的问题。 如何循环和传递 ID,以便它们可以均匀地连接到所有节点树?
考虑以下 HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Document</title>
</head>
<body>
<ul class="menu">
<div class="itm">home</div>
<div class="itm">About us</div>
<div class="itm">Contact us</div>
</ul>
<div id="idone" class="classone">
<li class="item1">First</li>
<li class="item2">Second</li>
<li class="item3">Third</li>
<div id="innerone"><h1>This Title</h1></div>
<div id="innertwo"><h2>Subheads</h2></div>
</div>
<div id="second" class="below">
<div class="inner">
<h1>welcome</h1>
<h1>another</h1>
<h2>third</h2>
</div>
</div>
</body>
</html>
使用当前的 python 代码,我最终得到了如图所示的截断树。我省略了图形数据库驱动程序。为了专注于密码,因为大多数图形数据库都遵循几乎相同的密码查询。
import json
from lxml import etree
from itertools import tee
from lxml import html
for n in dom_tree.iter():
cursor = Cypher("CREATE (t:node {tag: %s} ) RETURN id(t)", params=(n.tag,))
parent_id = cursor.fetchone()[0] # get last inserted ID
ag.commit()
print(f"Parent:{n.tag}")
for x in n.iterchildren():
cursor = Cypher("CREATE (x:node {tag: %s} ) RETURN id(x)", params=(x.tag,))
xid = cursor.fetchone()[0] # get last inserted ID
ag.commit()
print(f"--------{x.tag}")
cx = Cypher("MATCH (p:node),(k:node) WHERE id(p) = %s AND id(k) = %s CREATE (p)-[:connect {name: p.name+ '->'+k.name}]->(k)", params=(eid, xid,))
【问题讨论】:
标签: python-3.x xpath neo4j lxml graph-databases