添加家长标签和美丽的汤

2024-06-16 16:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有许多HTML页面,其中包含以下代码片段的各个部分:

<div class="footnote" id="footnote-1">
<h3>Reference:</h3>
<table cellpadding="0" cellspacing="0" class="floater" style="margin-bottom:0;" width="100%">
<tr>
<td valign="top" width="20px">
<a href="javascript:void(0);" onclick='javascript:toggleFootnote("footnote-1");' title="click to hide this reference">1.</a>
</td>
<td>
<p> blah </p>
</td>
</tr>
</table>
</div>

我可以成功地解析HTML并提取这些相关的标记

^{pr2}$

现在,我需要为这些添加新的父标记,以便代码片段如下:

<div class="footnote-out"><CODE></div>

但我找不到在bs4中添加父标记的方法,使它们能够支撑已识别的标记。在识别的标记之后的外接程序之前插入()。在

我一开始就试着用绳子操作:

for tags in soup.find_all(attrs={"footnote"}):
      tags = BeautifulSoup("""<div class="footnote-out">"""+str(tags)+("</div>"))

但我认为这不是最好的课程。在

谢谢你的帮助。刚开始使用bs/bs4,但似乎无法破解这个问题。在


Tags: 代码标记divhtmltagstablejavascriptout
1条回答
网友
1楼 · 发布于 2024-06-16 16:53:53

这个怎么样:

def wrap(to_wrap, wrap_in):
    contents = to_wrap.replace_with(wrap_in)
    wrap_in.append(contents)

简单示例:

^{pr2}$

文档示例:

for footnote in soup.find_all("div", "footnote"):
    new_tag = soup.new_tag("div")
    new_tag['class'] = 'footnote-out'
    wrap(footnote, new_tag)

相关问题 更多 >