【发布时间】:2015-08-28 15:07:51
【问题描述】:
我正在编写一个允许将 html 文档转换为 reveal.js 幻灯片的 python 脚本。为此,我需要在<section> 标记内包装多个标记。
使用wrap() 方法可以轻松地将单个标签包装在另一个标签中。但是我不知道如何包装多个标签。
一个例子澄清一下,原文html:
html_doc = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<h1 id="first-paragraph">First paragraph</h1>
<p>Some text...</p>
<p>Another text...</p>
<div>
<a href="http://link.com">Here's a link</a>
</div>
<h1 id="second-paragraph">Second paragraph</h1>
<p>Some text...</p>
<p>Another text...</p>
<script src="lib/.js"></script>
</body>
</html>
"""
"""
我想将<h1> 及其下一个标签包装在<section> 标签内,如下所示:
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<section>
<h1 id="first-paragraph">First paragraph</h1>
<p>Some text...</p>
<p>Another text...</p>
<div>
<a href="http://link.com">Here's a link</a>
</div>
</section>
<section>
<h1 id="second-paragraph">Second paragraph</h1>
<p>Some text...</p>
<p>Another text...</p>
</section>
<script src="lib/.js"></script>
</body>
</html>
我是这样选择的:
from bs4 import BeautifulSoup
import itertools
soup = BeautifulSoup(html_doc)
h1s = soup.find_all('h1')
for el in h1s:
els = [i for i in itertools.takewhile(lambda x: x.name not in [el.name, 'script'], el.next_elements)]
els.insert(0, el)
print(els)
输出:
[<h1 id="first-paragraph">First paragraph</h1>, 'First paragraph', '\n ', <p>Some text...</p>, 'Some text...', '\n ', <p>Another text...</p>, 'Another text...', '\n ', <div><a href="http://link.com">Here's a link</a> </div>, '\n ', <a href="http://link.com">Here's a link</a>, "Here's a link", '\n ', '\n\n ']
[<h1 id="second-paragraph">Second paragraph</h1>, 'Second paragraph', '\n ', <p>Some text...</p>, 'Some text...', '\n ', <p>Another text...</p>, 'Another text...', '\n\n ']
选择是正确的,但我看不到如何将每个选择包装在 <section> 标记内。
【问题讨论】:
-
你能编辑你的帖子并显示预期的输出吗?
-
请发布预期输出。
-
我添加了显式输出。
标签: python beautifulsoup