在第一次出现< table>

q3qa4bjr  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(349)

我的html如下所示:

<table class="table table-dark"><thead>
</thead></table>`

还有其他的 <table> html页面上的标签。我想要它,这样我可以插入另一个 <table> 在上面的元素之后 <table> 发生。我试过使用 BeautifulSoup 要查找第一个表,请执行以下操作:

soup = bs4.BeautifulSoup(filedata, 'html.parser')
        first_table = soup.find_all("table")[0]
    dashboard_result = dashboard.run()
    filedata = filedata.replace(first_table, '</table>' + dashboard_result)

当前的“解决方案”将覆盖并且不包含任何与.replace方法不匹配的内容,即filedata在html页面中不包含任何其他内容。如果我只是使用一个通用的 .replace("</table>", dashboard_result) 它将覆盖所有 </table> 标签。

wyyhbhjk

wyyhbhjk1#

如果我理解正确,您可以使用 insert_after() 方法。
另外,由于您只需要第一个表标记,因此请使用 find() 而不是 find_all()[0] ```
from bs4 import BeautifulSoup

html = """

soup.find("table").insert_after(soup.new_tag('NEW TABLE'))

print(soup.prettify())

输出:

相关问题