3

以下代码用于从 html 中获取连续的文本段。

    for text in soup.find_all_next(text=True):
        if isinstance(text, Comment):
            # We found a comment, ignore
            continue
        if not text.strip():
            # We found a blank text, ignore
            continue
        # Whatever is left must be good
        print(text)

文本项目由结构标签(如<div>or )和<br>格式化标签(如<em>和)分解<strong>。这给我进一步解析文本带来了一些不便,我希望能够在忽略文本内部的任何格式标记的同时获取连续的文本项。

例如,soup.find_all_next(text=True)将获取 html 代码<div>This is <em>important</em> text</div>并返回单个字符串,This is important text而不是三个字符串This isimportanttext.

我不确定这是否清楚......如果不是,请告诉我。

编辑:我逐个文本项浏览 html 文本项的原因是,我只是在看到特定的“开始”评论标签后才开始步行,而当我到达特定的“结束”评论标签时我会停下来. 在需要逐项遍历的情况下,是否有任何解决方案有效?我正在使用的完整代码如下。

soup = BeautifulSoup(page)
for instanceBegin in soup.find_all(text=isBeginText):
    # We found a start comment, look at all text and comments:
    for text in instanceBegin.find_all_next(text=True):
        # We found a text or comment, examine it closely
        if isEndText(text):
            # We found the end comment, everybody out of the pool
            break
        if isinstance(text, Comment):
            # We found a comment, ignore
            continue
        if not text.strip():
            # We found a blank text, ignore
            continue
        # Whatever is left must be good
        print(text)

如果传递给它们的字符串与我的开始或结束注释标签匹配,则这两个函数返回isBeginText(text)true 。isEndText(text)

4

2 回答 2

4

如果你抓取包含你的子元素的父元素并执行get_text(),BeautifulSoup 会为你去掉所有的 html 标签,只返回一个连续的文本字符串。

你可以在这里找到一个例子

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.get_text())
于 2016-02-18T04:31:20.147 回答
2

如何使用find_all_next两次,每个开始和结束标记一次,并获取两个生成列表的差异?

例如,我将使用BeautifulSoup 文档中html_doc的修改版本:

import bs4

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<!-- START--><a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p><!-- END -->

<p class="story">...</p>
"""

soup = bs4.BeautifulSoup(html_doc, 'html.parser')
comments = soup.findAll(text=lambda text:isinstance(text, bs4.Comment))

# Step 1: find the beginning and ending markers
node_start = [ cmt for cmt in comments if cmt.string == " START" ][0]
node_end = [ cmt for cmt in comments if cmt.string == " END " ][0]

# Step 2, subtract the 2nd list of strings from the first
all_text = node_start.find_all_next(text=True)
all_after_text = node_end.find_all_next(text=True)

subset = all_text[:-(len(all_after_text) + 1)]
print(subset)

# ['Lacie', ' and\n', 'Tillie', ';\nand they lived at the bottom of a well.']
于 2016-02-18T06:47:58.693 回答