【问题标题】:BeautifulSoup joins words in different paragraphsBeautifulSoup 连接不同段落中的单词
【发布时间】:2019-04-16 15:28:32
【问题描述】:

我有一个需要使用的 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()

输入 HTML:

&lt;p&gt;Paragraph1。 1号线&lt;/p&gt;

&lt;p&gt;Line 2&lt;p&gt;

预期输出:

第 1 段。 第 1 行第 2 行

实际输出: 第 1 段。 Line1Line2

【问题讨论】:

  • 你错过了一件事,p = soup.find_all("p"),然后迭代该列表。请发布完整的html

标签: python-3.x beautifulsoup epub


【解决方案1】:

你可以这样做。一旦你得到了 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

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多