我有一段这样的 HTML:
<figure>
<img src=".." alt=".." />
Some text that I have to wrap in <code>figcaption</code>
</figure>
而且我正在尝试将 <img> 之后的所有内容包装起来在<figcaption> .这可能吗?
next_elements可以很好地获取我想要的元素,但会返回一个生成器,它不能很好地与 wrap 配合使用方法。
请您参考如下方法:
这是一种方法:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("""
... <figure>
... <img src=".." alt=".." />
... Some text that I have to wrap in <code>figcaption</code>
... </figure>
... """)
>>> for figure in soup.find_all("figure"):
... img = figure.find("img")
... if img is not None:
... figcaption = soup.new_tag("figcaption")
... for el in list(img.next_siblings):
... figcaption.append(el)
... img.insert_after(figcaption)
...
>>> soup
<html><body><figure>
<img alt=".." src=".."/><figcaption>
Some text that I have to wrap in <code>figcaption</code>
</figcaption></figure></body></html>
一些注意事项:
我们使用
next_siblings, 它只返回我们实际需要的元素,而不是next_elements,这将持续到figure结束之后元素。我们包装
next_siblings与list()要创建一个浅拷贝,我们可以迭代 - 否则,由于附加el的行为至figcaption将其从文档树中的先前位置删除,这将修改我们要迭代的序列,即 a bad idea .我们本可以使用find_next_siblings()(它也返回一个列表),但上面的版本更明确。因为我们已经删除了
img的所有下一个兄弟节点|从他们原来在文档树中的位置,我们需要做的就是追加figcaption(现在包含它们)紧接在img之后元素。对于人类来说,空格的放置不再是直觉上的“正确”,但修复它需要大量的额外工作,而且可能不值得。
