【发布时间】:2012-09-14 18:48:03
【问题描述】:
我正在尝试使用BeautifulSoup 提取一些文本。为此,我正在使用get_text() 函数。
我的问题是文本包含</br> 标签,我需要将它们转换为结束行。我怎样才能做到这一点?
【问题讨论】:
标签: beautifulsoup
我正在尝试使用BeautifulSoup 提取一些文本。为此,我正在使用get_text() 函数。
我的问题是文本包含</br> 标签,我需要将它们转换为结束行。我怎样才能做到这一点?
【问题讨论】:
标签: beautifulsoup
正则表达式应该可以解决问题。
import re
s = re.sub('<br\s*?>', '\n', yourTextHere)
希望这会有所帮助!
【讨论】:
您可以使用 BeautifulSoup 对象本身或它的任何元素来做到这一点:
for br in soup.find_all("br"):
br.replace_with("\n")
【讨论】:
soup.text 删除其他html标签,而当前接受的答案不提供这种可能性。
br.replace_with("\n" + br.text) 的操作。这个标签是邪恶的......
正如official doc 所说:
您可以指定一个字符串用于将文本位连接在一起:soup.get_text("\n")
【讨论】:
添加到 Ian 和 dividebyzero 的帖子/cmets 中,您可以一次性有效地过滤/替换 许多 标签:
for elem in soup.find_all(["a", "p", "div", "h3", "br"]):
elem.replace_with(elem.text + "\n\n")
【讨论】:
与其用 \n 替换标签,不如在所有重要标签的末尾添加一个 \n 可能会更好。
从@petezurich 窃取列表:
for elem in soup.find_all(["a", "p", "div", "h3", "br"]):
elem.append('\n')
【讨论】:
如果您调用element.text,您将获得没有 br 标记的文本。
也许您需要为此目的定义自己的自定义方法:
def clean_text(elem):
text = ''
for e in elem.descendants:
if isinstance(e, str):
text += e.strip()
elif e.name == 'br' or e.name == 'p':
text += '\n'
return text
# get page content
soup = BeautifulSoup(request_response.text, 'html.parser')
# get your target element
description_div = soup.select_one('.description-class')
# clean the data
print(clean_text(description_div))
【讨论】:
您也可以使用 get_text(separator = '\n', strip = True) :
from bs4 import BeautifulSoup
bs=BeautifulSoup('<td>some text<br>some more text</td>','html.parser')
text=bs.get_text(separator = '\n', strip = True)
print(text)
>>
some text
some more text
它对我有用。
【讨论】: