gpt4 book ai didi

python - 如何获取带有与浏览器 View 而不是 html 源匹配的换行符的文本(使用 python 和 beautifulsoup)

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:44 25 4
gpt4 key购买 nike

当我使用 Python 中 BeautifulSoup 模块的 get_text() 函数时,它返回带有与 HTML 源匹配的换行符的文本。

但是,我希望换行符能够模仿您在浏览器中看到的内容(例如,忽略 HTML 源代码中的换行符、<br> 标签的一个换行符、<p> 标签之间的两个换行符) .

from bs4 import BeautifulSoup

some_html = """<p>Some
sample html<br>
new line
<p>New paragraph"""

plain_text = BeautifulSoup(some_html,"html.parser").get_text()

预期结果:

Some sample html
new line

New paragraph

实际结果:

Some 
sample html
new line
New paragraph

最佳答案

我最终使用了一些替代品。它适用于我正在使用的 HTML。

from bs4 import BeautifulSoup

sample = """<p>Some
sample html<br>
new line
<p>New paragraph"""

# Remove all line breaks in the source
sample_remove_line_breaks = re.sub(r'\r?\n', ' ', sample)

# Add line breaks for each `<br>` and `<p>` tag
sample_add_html_line_breaks = re.sub(r'<p>', '\n\n<p>', re.sub(r'<br>', '<br>\n', sample_remove_line_breaks))

plain_text = BeautifulSoup(sample_add_html_line_breaks,"html.parser").get_text()

关于python - 如何获取带有与浏览器 View 而不是 html 源匹配的换行符的文本(使用 python 和 beautifulsoup),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58402563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com