将</ br>转换为结束行

MBZ*_*MBZ 32 beautifulsoup

我正在尝试使用提取一些文本BeautifulSoup.我正在get_text()为此目的使用功能.

我的问题是文本包含</br>标签,我需要将它们转换为结束行.我怎样才能做到这一点?

Ian*_*non 58

您可以使用BeautifulSoup对象本身或其中的任何元素来执行此操作:

for br in soup.find_all("br"):
    br.replace_with("\n")
Run Code Online (Sandbox Code Playgroud)

  • 这个答案的好处是,您可以在之后调用 `soup.text` 来删除其他 html 标签,而当前接受的答案并没有提供这种可能性。 (2认同)
  • 注意这一点,您可能最终会无意间丢失一些内容。您可能需要执行类似“ br.replace_with(“ \ n” + br.text)`的操作。这个标签是邪恶的... (2认同)

小智 38

正如官方文件所说:

您可以指定用于将文本位连接在一起的字符串:soup.get_text("\n")

  • @Sasha我不确定你的意思 - 我相信“文本位”是指由标签分隔的文本。正如您所建议的那样,当我运行它时,我当然不会在每对单词之间换行。 (2认同)

小智 9

您也可以使用 \xe2\x80\x8d\xe2\x80\x8d\xe2\x80\x8d get_text(separator = '\\n', strip = True)

\n
from bs4 import BeautifulSoup\nbs=BeautifulSoup('<td>some text<br>some more text</td>','html.parser')\ntext=bs.get_text(separator = '\\n', strip = True)\nprint(text)\n >> \nsome text\nsome more text\n
Run Code Online (Sandbox Code Playgroud)\n

这个对我有用。

\n


mbi*_*tte 5

正则表达式可以解决问题。

import re
s = re.sub('<br\s*?>', '\n', yourTextHere)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


pet*_*ich 5

添加到 Ian 和dividebyzero 的帖子/评论中,您可以这样做来一次性有效地过滤/替换许多标签:

for elem in soup.find_all(["a", "p", "div", "h3", "br"]):
    elem.replace_with(elem.text + "\n\n")
Run Code Online (Sandbox Code Playgroud)