Python:将 HTML 片段分隔为段落
我有一段包含段落的 HTML 片段。 (我的意思是 p
标签。)我想将字符串分成不同的段落。例如:
'''
<p class="my_class">Hello!</p>
<p>What's up?</p>
<p style="whatever: whatever;">Goodbye!</p>
'''
应该变成:
['<p class="my_class">Hello!</p>',
'<p>What's up?</p>'
'<p style="whatever: whatever;">Goodbye!</p>']
解决这个问题的好方法是什么?
I have a snippet of HTML that contains paragraphs. (I mean p
tags.) I want to split the string into the different paragraphs. For instance:
'''
<p class="my_class">Hello!</p>
<p>What's up?</p>
<p style="whatever: whatever;">Goodbye!</p>
'''
Should become:
['<p class="my_class">Hello!</p>',
'<p>What's up?</p>'
'<p style="whatever: whatever;">Goodbye!</p>']
What would be a good way to approach this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的字符串仅包含段落,您也许可以使用精心设计的正则表达式和
re.split()
。但是,如果您的字符串是更复杂的 HTML,或者并不总是有效的 HTML,您可能需要查看 BeautifulSoup 包。用法如下:
If your string only contains paragraphs, you may be able to get away with a nicely crafted regex and
re.split()
. However, if your string is more complex HTML, or not always valid HTML, you might want to look at the BeautifulSoup package.Usage goes like:
使用
lxml.html
将HTML解析为您想要的形式。这基本上与推荐 BeautifulSoup 的人的建议相同,只是 lxml 仍在积极开发中,而 BeatifulSoup 的开发速度已经放缓。Use
lxml.html
to parse the HTML into the form you want. This is essentially the same advice as the people who are recommending BeautifulSoup, exceptlxml
is still being actively developed and BeatifulSoup development has slowed.使用 BeautifulSoup 解析 HTML 并迭代段落。
Use BeautifulSoup to parse the HTML and iterate over the paragraphs.
xml.etree(标准库)或 lxml.etree(增强版)使这很容易做到,但我不会得到答案,因为我不记得确切的语法。我一直把它与类似的包混在一起,每次都必须重新查找。
The xml.etree (std lib) or lxml.etree (enhanced) make this easy to do, but I'm not going to get the answer cred for this because I don't remember the exact syntax. I keep mixing it up with similar packages and have to look it up afresh every time.