gpt4 book ai didi

python - HTML 结构转化为网络图

转载 作者:行者123 更新时间:2023-12-02 05:07:19 26 4
gpt4 key购买 nike

我想做的是将 HTML 站点 DOM(文档对象模型)表示为网络图,然后用该图进行一些统计计算(例如度数、介数、邻近度、当然绘图等)。 )。我找不到任何直接执行此操作的库或之前的 SO 帖子。我的想法是使用 BeautifulSoup 库,然后使用 Networkx 库。我尝试编写一些循环遍历 HTML 结构的每个元素的代码(使用 recursive=True)。但我不知道如何识别每个唯一的标签(您在这里看到,在图中添加第二个 h1 节点会覆盖第一个节点,对于 parent 来说也是如此,所以图表最终是完全错误的)。

import networkx as nx
import bs4
from bs4 import BeautifulSoup
ex0 = "<html><head><title>Are you lost ?</title></head><body><h1>Lost on the Intenet ?</h1><h1>Don't panic, we will help you</h1><strong><pre> * <----- you are here</pre></strong></body></html>"
soup = BeautifulSoup(ex0)
G=nx.Graph()
for tag in soup.findAll(recursive=True):
G.add_node(tag.name)
G.add_edge(tag.name, tag.findParent().name)
nx.draw(G)
G.nodes
#### NodeView(('html', '[document]', 'head', 'title', 'body', 'h1', 'strong', 'pre'))

enter image description here

关于如何完成的任何想法(包括完全不同的方法)。谢谢

PS:图表可以是有向的,也可以是无向的,我不在乎。

最佳答案

您可以循环访问每个 BeautifulSoup 对象的 content 属性。要显示标签,只需利用 nx.draw 中的 with_labels 属性即可:

import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from bs4 import BeautifulSoup as soup
ex0 = "<html><head><title>Are you lost ?</title></head><body><h1>Lost on the Intenet ?</h1><h1>Don't panic, we will help you</h1><strong><pre> * <----- you are here</pre></strong></body></html>"
d = soup(ex0, 'html.parser')
def _traverse_html(_d:soup, _graph:nx.Graph, _counter, _parent=None) -> None:
for i in _d.contents:
if i.name is not None:
try:
_name_count = _counter.get(i.name)
if _parent is not None:
_graph.add_node(_parent)
_graph.add_edge(_parent, i.name if not _name_count else f'{i.name}_{_name_count}')
_counter[i.name] += 1
_traverse_html(i, _graph, _counter, i.name)
except AttributeError:
pass

_full_graph = nx.Graph()
_traverse_html(d, _full_graph, defaultdict(int))
nx.draw(_full_graph, with_labels = True)
plt.show()

enter image description here

关于python - HTML 结构转化为网络图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53817270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com