python - 如何使用 BeautifulSoup 从一层获取文本?

标签 python beautifulsoup

我有一些网页,我想按级别对所有文本内容进行排序。 但我不知道会有什么标签。

html = BeautifulSoup("<a><b>text1</b><b>text2</b></a><c>text3</c>")
print(html.prettify())

#<html>
#  <body>
#      <a>
#         <b>
#           text1
#         </b>
#         <b>
#           text2
#         </b>
#      </a>
#      <c>
#         text3
#      </c>
#  </body>
#</html>

如何使用 bs4 获取所有文本 block ?

level1 = ['text3']
level2 = ['text1', 'text2']

依此类推...结果的结构可以不同。

感谢您的回复!

最佳答案

解决这个问题的方法之一是使用搜索树算法(例如深度优先搜索)

from bs4 import NavigableString

def dfs(tree, level):
    for node in tree.children:
        if isinstance(node, NavigableString):
            if not node.string == '':
                print node.string, level
            return
        dfs(node, level + 1)

dfs(html, 0)

它将打印

# text1 4
# text2 4
# text3 3

因此,如果有必要,我们可以制作一个包装器将结果保存到字典中。例如,像这样:

from bs4 import NavigableString

def dfs(tree):
    level = 0
    levDic = {}

    dfs1(tree, level, levDic)
    return levDic


def dfs1(tree, level, levDic):
    for node in tree.children:
        if isinstance(node, NavigableString):
            if not node.string == '':
                if level in levDic.keys():
                    levDic[level].append(node.string)
                else:
                    levDic[level] = [node.string]
            return
        dfs1(node, level + 1, levDic)
    return

print dfs(html)
# {3: [u'text3'], 4: [u'text1', u'text2']}

关于python - 如何使用 BeautifulSoup 从一层获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25888357/

相关文章:

python - 如何使用 ZenHub API 设置问题管道

Python unittest 测试 MongoDB 随机失败

使用 beautifulsoup 对表进行 Python 迭代仅给出第一列

selenium - 使用 Python 从 JSP 网站抓取表

python - 如何抓取 Flipkart 评论中的评论数据 阅读更多内容

python - 我应该使用什么纯 Python 库来抓取网站?

python - Beautifulsoup 发现没有值的标签和属性?

python - 将 XML 字符串分成三个 float

python - 开发 Web 应用程序的一般指南

machine-learning - 具有固定协方差的高斯核密度估计(使用python)