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

标签 python html beautifulsoup

当我使用 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/

相关文章:

html - 中心固定宽度元素,div 填充额外空间

html - 将 div 扩展到屏幕尺寸之外

python - BeautifulSoup 返回空 td 标签

Python 打印缩进

python - 读取和写入 40GB CSV 时出现内存错误...我的泄漏在哪里?

python - 如何从 docx 创建的表中删除空白列?

Python 从 tripadvisor 抓取 'things to do'

python - Jupyter 笔记本 : Multiple notebook to one kernel?

html - 使按钮在鼠标悬停时可见

python - 如何从列表中的表行中获取表头和表数据?