Python:将 HTML 片段分隔为段落

发布于 2024-08-21 23:56:12 字数 435 浏览 6 评论 0原文

我有一段包含段落的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

缘字诀 2024-08-28 23:56:12

如果您的字符串仅包含段落,您也许可以使用精心设计的正则表达式和re.split()。但是,如果您的字符串是更复杂的 HTML,或者并不总是有效的 HTML,您可能需要查看 BeautifulSoup 包。

用法如下:

from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup(some_html)

paragraphs = list(unicode(x) for x in soup.findAll('p'))

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:

from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup(some_html)

paragraphs = list(unicode(x) for x in soup.findAll('p'))
厌味 2024-08-28 23:56:12

使用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, except lxml is still being actively developed and BeatifulSoup development has slowed.

故事还在继续 2024-08-28 23:56:12

使用 BeautifulSoup 解析 HTML 并迭代段落。

Use BeautifulSoup to parse the HTML and iterate over the paragraphs.

琉璃繁缕 2024-08-28 23:56:12

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文