如何获取与浏览器视图而不是html源代码相匹配的换行文本(使用python和beautifulsoup)

2024-04-20 09:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

Tags: sampletext标记brnewget源代码html
1条回答
网友
1楼 · 发布于 2024-04-20 09:26:02

最后我用了一些替代品。它适用于我正在使用的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()

相关问题 更多 >