Skip to main content
 首页 » 编程设计

python之将所有 next_elements 包装在 BeautifulSoup 中

2024年11月01日10www_RR

我有一段这样的 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> 

一些注意事项:

  1. 我们使用 next_siblings , 它只返回我们实际需要的元素,而不是 next_elements ,这将持续到 figure 结束之后元素。

  2. 我们包装next_siblings与 list()要创建一个浅拷贝,我们可以迭代 - 否则,由于附加 el 的行为至 figcaption将其从文档树中的先前位置删除,这将修改我们要迭代的序列,即 a bad idea .我们本可以使用 find_next_siblings() (它也返回一个列表),但上面的版本更明确。

  3. 因为我们已经删除了img 的所有下一个兄弟节点|从他们原来在文档树中的位置,我们需要做的就是追加 figcaption (现在包含它们)紧接在 img 之后元素。

  4. 对于人类来说,空格的放置不再是直觉上的“正确”,但修复它需要大量的额外工作,而且可能不值得。