我正在尝试使用提取一些文本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)
小智 9
您也可以使用 \xe2\x80\x8d\xe2\x80\x8d\xe2\x80\x8d get_text(separator = '\\n', strip = True)
:
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正则表达式可以解决问题。
import re
s = re.sub('<br\s*?>', '\n', yourTextHere)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
添加到 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)
归档时间: |
|
查看次数: |
11959 次 |
最近记录: |