簡體   English   中英

python,創建嵌套的 html 節點。 我如何從圖中遍歷 Dom 樹並找到它的直接子級並從中創建 html 文件?

[英]python, create nested html nodes. How do i traverse the Dom tree from a graph and find it's immediate children and create an html file from it?

我正在嘗試遞歸提取保存在圖形數據庫中的 DOM 樹,以將它們精細地重寫為 HTML、JSON 或其他模板文件。 我需要一種簡單的方法來提取和控制 DOM 節點,將它們重寫為任何需要的模板格式,這種格式可以集成到變量插值至關重要的 CMS 或 MVC 開發中。

我使用遞歸的嘗試失敗了,因為我對使用什么作為下一個節點父節點或子節點感到困惑。

我需要做的是訪問具有以下樹,我需要創建一個等效的 HTML 文件,現在使用 beautifulsoup 或其他實用程序。

   html
        head
            title
        body
            div
            div
                ul
                    li

使用以下代碼,如果沒有遞歸 function,我可以得到直接的孩子,從而產生以下值:

|> parent Id: 844424930131969 --- parent tag HTML
    child id 844424930131970 child tag: head
    child id 844424930131973 child tag: body

或以下 html 文件:

<html>
 <head>
 </head>
 <body>
 </body>
</html>

我如何通過d才能成為下一個遞歸的一部分,在那里我可以獲得它的孩子?

cursor = ag.execCypher("MATCH (n:node {tag: 'html'}) RETURN n")    
t = [x[0].id for x in cursor]
print(t[0])

def graph_dom(t_id):
    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}")
    parent_tag = soup.new_tag(name=p[0]["tag"])
    soup.append(parent_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"])
        parent_tag.append(children_tag)
        dt = d[0]["tag"]
        did = d[0].id
        print(f"child id {did} child tag: {dt}")        
    # graph_dom()   # I need to add a recursive argument   
        
graph_dom(t[0])

file_soup = soup.prettify()
with open("helloworld.html", "w") as file:
    file.write(str(file_soup))

我認為您應該在子循環中遞歸調用 graph_dom(did) 。

cursor = ag.execCypher("MATCH (n:node {tag: 'html'}) RETURN n")    
t = [x[0].id for x in cursor]
print(t[0])

def graph_dom(t_id):
    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}")
    parent_tag = soup.new_tag(name=p[0]["tag"])
    soup.append(parent_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"])
        parent_tag.append(children_tag)
        dt = d[0]["tag"]
        did = d[0].id
        print(f"child id {did} child tag: {dt}")        
        graph_dom(did)   # Call graph_dom recursively.   
        
graph_dom(t[0])

file_soup = soup.prettify()
with open("helloworld.html", "w") as file:
    file.write(str(file_soup))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM