python - BeautifulSoup 删除嵌套标签

标签 python python-2.7 web-scraping beautifulsoup

我正在尝试使用 BeautifulSoup 制作一个通用的刮刀,我正在尝试检测在其下可直接使用文本的标签。

考虑这个例子:

<body>
<div class="c1">
    <div class="c2">
        <div class="c3">
            <div class="c4">
                <div class="c5">
                    <h1> A heading for section </h1>
                </div>
                <div class="c5">
                    <p> Some para </p>
                </div>
                <div class="c5">
                    <h2> Sub heading </h2>
                    <p> <span> Blah Blah </span> </p>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

这里我的目标是提取 (div with class c4) 因为它包含所有文本内容。 c1 - c3 之前的 div 的其余部分对我来说只是包装。

我提出的一种识别节点的可能方法是:

if node.find(re.compile("^h[1-6]"), recursive=False) is not None:
    return node.parent.parent

但对于本例来说太具体了。

是否有任何优化方法可以在一级递归中查找文本。即如果我做类似的事情

node.find(text=True, recursion_level=1)

那么它应该返回仅考虑直系子代的文本。

到目前为止我的解决方案,不确定是否适用于所有情况。

def check_for_text(node):
    return node.find(text=True, recursive=False)

def check_1_level_depth(node):
    if check_for_text(node):
        return check_for_text(node)

    return map(check_for_text, node.children)

对于上面的代码:node是当前正在检查的soup的一个元素,即div、span等。 请假设我正在处理 check_for_text() 中的所有异常(AttributeError: 'NavigableString')

最佳答案

结果我必须编写一个递归函数来消除具有单个子项的标签。这是代码:

# Pass soup.body in following
def process_node(node):
    if type(node) == bs4.element.NavigableString:
        return node.text
    else:
        if len(node.contents) == 1:
            return process_node(node.contents[0])
        elif len(node.contents) > 1:
            return map(process_node, node.children)

到目前为止,它运行良好且快速。

关于python - BeautifulSoup 删除嵌套标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19324530/

相关文章:

python - 如何漂亮地打印嵌套字典?

google-apps-script - Google 文档从脚本调用 ImportXML

python - Selenium python - 元素在点不可点击

python - 如何获取 Facebook 公共(public)页面内容访问权限只是为了提取数据?

python - 有两个不同的 TensorFlow,如何完全卸载它们?

python - 类型错误 : '<' not supported between instances - objects

python - 从 Sublime Text 2 中的值列表填充片段

python - 使用 python 计算抛物线

python - 按范围切片

python - 带有 except block 的变量范围 : Difference between Python 2 and 3