如何在保持兄弟姐妹beautifulsoup的同时插入和删除标签?

问题描述 投票:0回答:1

我收到一个 html 格式的表格,需要遍历它以查找设置了

rowspan
的标签。一旦找到带有
rowspan=<a number>
的单元格,我需要插入一段代码:

<tr>
<th rowspan="14" >Words</th>
<td style="height: 30px;"></td>
<td style="text-align: center; height: 30px;"></td>
<td style="height: 30px;"></td>
<td style="text-align: right; padding: 7px; min-width: 75px"></td>
<td style="height: 30px;"></td>
<td style="height: 30px;"></td>
<td style="height: 30px;"></td>
</tr>\n

作为当前行上方的行。然后,我需要从当前行中删除这个

<th>

例如,这是我要搜索的代码:

<table border="1" class="dataframe" style="border: 1px solid grey">
<tbody>
    <tr>
      <th>Records</th>
      <th>Worth</th>
      <td>30</td>
      <td>is</td>
      <td>50</td>
      <td>0</td>
      <td>good</td>
      <td></td>
    </tr>
    <tr>
      <!-- this is the code im looking for -->
      <th rowspan="13" valign="top">Reports</th>
      <!--  -->
      <th>Worth</th>
      <td>30</td>
      <td>=</td>
      <td>40</td>
      <td>0</td>
      <td>bad</td>
      <td></td>
    </tr>
    <tr>
      <th>Worth</th>
      <td>is</td>
      <td>44</td>
      <td>400.0</td>
      <td></td>
      <td>bad</td>
      <td></td>
    </tr>
</tbody>
</table>

因此,一旦我找到带有

<th>
rowspan
,我需要将该块插入到其上方的行,然后从当前行中删除
<th>
。这就是我现在的做法:

for child in soup.tbody.descendants:
        if child.name == 'th':
            if 'rowspan' in child.attrs:
                new_row = <<that block from above>>
                crazy_tag = bs4.BeautifulSoup(new_row, 'html.parser')
                x = child.find_previous('tr')
                x.insert_before(crazy_tag)
                child.extract()

我正在寻找的输出是这样的:

<table border="1" class="dataframe" style="border: 1px solid grey">
<tbody>
    <tr>
      <th>Records</th>
      <th>Worth</th>
      <td>30</td>
      <td>is</td>
      <td>50</td>
      <td>0</td>
      <td>good</td>
      <td></td>
    </tr>
    <tr>
      <th rowspan="14" >Words</th>
      <td style="height: 30px;"></td>
      <td style="text-align: center; height: 30px;"></td>
      <td style="height: 30px;"></td>
      <td style="text-align: right; padding: 7px; min-width: 75px"></td>
      <td style="height: 30px;"></td>
      <td style="height: 30px;"></td>
      <td style="height: 30px;"></td>
    </tr>
    <tr>
      <th>Worth</th>
      <td>30</td>
      <td>=</td>
      <td>40</td>
      <td>0</td>
      <td>bad</td>
      <td></td>
    </tr>
    <tr>
      <th>Worth</th>
      <td>is</td>
      <td>44</td>
      <td>400.0</td>
      <td></td>
      <td>bad</td>
      <td></td>
    </tr>
</tbody>
</table>

好消息是,我的代码做了我想要的事情,并且得到了想要的输出。坏消息是,在完成之前我还必须对此 html 执行其他操作。在我执行此操作并继续循环后代之后,下一次迭代给我 None 。我认为 extract() 保持了树的结构完整,但似乎我插入的块或我删除的行都没有保留树结构。有什么想法吗?

我的问题基本上可以归结为:如何将一些 html 插入到一个漂亮的 soup 对象中并提取一行而不破坏文档中的兄弟关系?

python html beautifulsoup tags
1个回答
0
投票

相反,

.insert_before()
/
.extract()
,您可以使用简单的
© www.soinside.com 2019 - 2024. All rights reserved.