How to convert selected HTML to Json?

前端 未结 6 865
迷失自我
迷失自我 2020-12-03 14:27

I want to save part of my html code into json as a file then recap back the html codes for editing. Any idea how can i do it?

6条回答
  •  醉酒成梦
    2020-12-03 15:17

    i use recursive function to handle it

    from bs4 import BeautifulSoup
    dic = dict()
    
    itt = 0
    
    def list_tree_names(node):
    global itt
    for child in node.contents:
        try:
            dic.update({child.name +"/"+ str(itt): child.attrs})
            itt += 1
            list_tree_names(node=child)
        except:
            dic.update({"text" +"/"+ str(itt): child})
            itt += 1
    
    
    soup = BeautifulSoup(data, "html.parser")
    

    data is the html text

    list_tree_names(soup)
    
    print(dic)
    

    you can see json file in https://github.com/celerometis/html2json

提交回复
热议问题