美丽汤将单词连接在不同的段落中



我有一个需要使用的 EPUB 文件。我正在尝试从文件中存在的HTML文件中提取文本。当我对提取的 HTML 内容运行soup.get_text()时,所有段落都连接在一起,将单词组合在一起。

我尝试用空格替换所有<br></br>标签。我还尝试将解析器从 html.parser 更改为 html5lib .

with self._epub.open(html_file) as chapter:
    html_content = chapter.read().decode('utf-8')
    html_content = html_content.replace('</br>', ' ')
    html_content = html_content.replace('<br>', ' ')
    soup = bs4.BeautifulSoup(html_content, features="html5lib")
    clean_content = soup.get_text()

输入网页:

<p>第1段。1号线</p>

<p> 2号线<p>

预期产出:

第1款.1号线 2号线

实际输出:第1款.1号线2号线

你可以这样做。一旦你得到html。

from bs4 import BeautifulSoup
html='''<p>Paragraph1. Line 1</p><p>Line 2<p>'''
    soup=BeautifulSoup(html,'html.parser')
    itemtext=''
    for item in soup.select('p'):
        itemtext+=item.text + ' '
    print(itemtext.strip())

输出:

Paragraph1. Line 1 Line 2

最新更新