首页 > 解决方案 > 如何使用 python beautifulesoup 在 html 文件中插入新行

问题描述

我正在使用 python 2.7,beautifulsoup。我有一个本地 html 文件,我想通过向表中附加新行来在表中插入信息。

从网上搜索后,我能够选择没有 id 的正确表。

import requests
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('./result.html'), 'html.parser')

table = soup.find(text="Beta").find_parent("table")
for row in table.find_all("tr")[1:]:
    print([cell.get_text(strip=True) for cell in row.find_all("td")])

这就是我想要做的。前:

<tr><td colspan="3"><hr></td></tr>
<tr><td>Beta</td><td>0.0883</td><td>-</td></tr>
<tr><td>Alpha</td><td>0.1115</td><td>-</td></tr>
</tbody>
</table>

后:

<tr><td colspan="3"><hr></td></tr>
<tr><td>Beta</td><td>0.0883</td><td>-</td></tr>
<tr><td>Alpha</td><td>0.1115</td><td>-</td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><td>Total Trade</td><td>2574</td><td>-</td></tr>
</tbody>
</table>

非常感谢。

标签: pythonbeautifulsoup

解决方案


new_tag = soup.new_tag("Your Tag") #add even more tags as needed
new_tag.append("Your Text")
# insert the new tag after the last tag using insert_after
the_last_tag_i_want_to_insert_after.insert_after(new_tag)

推荐阅读