Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用BeautifulSoup获得标签的最大嵌套_Python_Html_Parsing_Beautifulsoup - Fatal编程技术网

Python 使用BeautifulSoup获得标签的最大嵌套

Python 使用BeautifulSoup获得标签的最大嵌套,python,html,parsing,beautifulsoup,Python,Html,Parsing,Beautifulsoup,我正在寻找一种方法,给定一个经过BeautifulSoup解析的文档,以找到嵌套的最高级别 例如,我需要magic_功能in: r = requests.get("http//example.com") soup = BeautifulSoup(r.text) depth = magic_function(soup) 例如,对于本文档,将返回4: <html> <body> <p> <strong>

我正在寻找一种方法,给定一个经过BeautifulSoup解析的文档,以找到嵌套的最高级别

例如,我需要
magic_功能
in:

r = requests.get("http//example.com")
soup = BeautifulSoup(r.text)
depth = magic_function(soup)
例如,对于本文档,将返回4:

<html>
    <body>
        <p>
            <strong>Some Text.</strong>
            <strong>Some Text.</strong>
            <strong>Some Text.</strong>
        </p>
        <p>
            <strong>Some Text.</strong>
            <strong>Some Text.</strong>
            <strong>Some Text.</strong>
        </p>
    </body>
</html>


一些文本。
一些文本。
一些文本。

一些文本。 一些文本。 一些文本。

我有一些想法:

  • BeautifulSoup中是否有这样的功能?查看文档和谷歌搜索对我毫无帮助

  • 有没有其他图书馆可以让我这样做?同样,谷歌搜索对我毫无用处,但我可能根本不知道该搜索什么

  • 我是否应该尝试使用我自己构建的函数遍历树?我真的不想,但我肯定能做到


  • 使用自己的
    magic_function()
    遍历树并不困难。您可以使用一个简单的递归函数,如:

    def magic_function(soup):
        if hasattr(soup, "contents") and soup.contents:
            return max([magic_function(child) for child in soup.contents]) + 1
        else:
            return 0
    
    您可能希望使用文档的顶级
    html
    标记调用函数,这样它就不会将
    soup
    对象中的嵌套计算为嵌套级别

    使用上述文档结构,此函数调用返回
    4

    >>> magic_function(soup.html)
    4
    

    在您的示例中,html只有一个子项,body只有一个子项,p只有一个子项。如果html有3个子元素,body有15个子元素,那么输出应该是什么呢;这不会改变结果。听起来不错!不过,要明确的是,模块中没有包含这种性质的功能?我不认为这是一个常见的问题。大多数人使用BS从网页中删除信息内容。我不知道有多少人对最大嵌套深度感兴趣;这个想法是抽象出HTML,而不是专注于它?不管怎样,你的答案解决了我的问题,所以我会接受。我想说的想法是使用HTML结构来导航并从页面中提取信息。我想我的评论是,更多的人(对我来说)使用Beautiful Soup来导航和提取页面或文档中的内容,而不是分析文档的结构——但这肯定是一个非常有效的用例。:-)