使用BeautifulSoup为餐桌添加美食,让它发挥作用



我在这里有这个片段:https://pastebin.com/cNviWz4a

这个想法是我清理一张桌子并更换它。

然而,当我在片段中这样做时,我会得到:https://pastebin.com/raw/6GF7XZck

我试着阅读告诉我这样做的文档:

from bs4 import BeautifulSoup
html = open("sample.html").read()
soup = BeautifulSoup(html)
new_div = soup.new_tag('div')
new_div.string="abcdef"

但我不理解。

我该如何添加一个表并添加

您可以创建新的汤并将其附加到<table>。例如:

from bs4 import BeautifulSoup
original_html = '''
<table>
</table>
'''
soup = BeautifulSoup(original_html, 'html.parser')
table = soup.find('table')
key = 'FOO'
dictDesc = {'FOO': 'BAR'}
# append new html to <table>
table.append(BeautifulSoup(f'''
<tr style="box-sizing: border-box;">
<th class="a-span" style="box-sizing: border-box; ">
<font size="3">{key}</font>
</th>
<td class="a-span "
style="box-sizing: border-box; ">
<font size="3">{dictDesc[key]}</font>
</td>
</tr>''', 'html.parser'))
print(soup.prettify())

打印:

<table>
<tr style="box-sizing: border-box;">
<th class="a-span" style="box-sizing: border-box; ">
<font size="3">
FOO
</font>
</th>
<td class="a-span" style="box-sizing: border-box; ">
<font size="3">
BAR
</font>
</td>
</tr>
</table>

最新更新