【问题标题】:How to find depth of <div> tag in html using python?如何使用python在html中查找<div>标签的深度?
【发布时间】:2015-04-18 15:04:55
【问题描述】:

我应该如何找到这个块的深度 -

<div>
    <div>
        <div>
        </div>
    </div>
</div>

在这种情况下,它应该是 3。 任何线索/代码都会有所帮助。

【问题讨论】:

标签: python html regex


【解决方案1】:

有很多方法可以做到这一点。不过,我会 not recommend 使用正则表达式来解析 XML。

一种方法是使用 Python 自带的HTMLParser

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.depth = 1

    def handle_starttag(self, tag, attrs):
        print 'Encountered %s at depth %d.' % (tag, self.depth)
        self.depth += 1

    def handle_endtag(self, tag):
        self.depth -= 1

if __name__ == '__main__':
    html = '''
    <div>
        <div>
            <div>
            </div>
        </div>
    </div>
    '''

    MyHTMLParser().feed(html)

运行此脚本会产生:

Encountered div at depth 1.
Encountered div at depth 2.
Encountered div at depth 3.

【讨论】:

  • 我建议将链接更改为 google.com 而不是 google.be
  • 谢谢罗丹!这很有帮助。
猜你喜欢
  • 2021-11-17
  • 2014-07-30
  • 2013-09-18
  • 1970-01-01
  • 2021-10-08
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
相关资源
最近更新 更多