【问题标题】:How to get beautiful soup get_text() to consider line spacing for paragraph tags如何获得漂亮的汤 get_text() 以考虑段落标签的行距
【发布时间】:2021-05-21 01:28:32
【问题描述】:

我正在尝试将 html 转换为文本。使用 BeautifulSoup 库。 但是,它不考虑段落标签的间距(或换行)

from bs4 import BeautifulSoup
test_input = '<html><p>this is sentence 1</p><p>this is sentence 2</p></html>'
soup = BeautifulSoup(test_input, 'html.parser')
print(soup.get_text())

输出:this is sentence 1this is sentence 2

期望:this is sentence 1 this is sentence 2

需要帮助了解 BeautifulSoup 是否可以以某种方式处理该问题,或者是否有任何替代库可以使用?

【问题讨论】:

  • 这两句话之间需要空格吗??
  • 是的。由于这些被原始 html 中的段落标签包围,我希望它们位于不同的行中,以便我知道这些是不同的段落
  • @NishantSaraswat :如果您找到了您要查找的内容,请将答案标记为正确。谢谢。

标签: python-3.x beautifulsoup


【解决方案1】:

你可以按照下面的方法做

from bs4 import BeautifulSoup
test_input = '<html><p>this is sentence 1</p><p>this is sentence 2</p></html>'
soup = BeautifulSoup(test_input, 'html.parser')
data = soup.find_all('p')
output = " ".join([p1.text for p1 in data])

输出将是

this is sentence 1 this is sentence 2

如果你想要它在新行中,只需更改此行

output = "\n".join([p1.text for p1 in data])

输出将是

this is sentence 1 
this is sentence 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-27
    • 2020-08-02
    • 2016-06-02
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多