python - 如何使用 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>
非常感谢。
解决方案
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)
推荐阅读
- flutter - 如何在不创建无休止的 TextEditingController 的情况下保存不同的 Textfield 值
- cucumber - 使用 WebdriverIO 和 Cucumber 上传文件
- php - 带有波斯文件名的php getimagesize
- javascript - 如何使用 JavaScript 在新窗口中从主页打开功能?
- javascript - 猫鼬不居住
- javascript - React - MUI - 无法取消选择多选中的所有项目
- google-cloud-platform - 如何跟踪 Google Cloud 公共数据集的变化?
- sql - 投射后“锚点和递归部分之间的类型不匹配”
- typescript - typescript 在保留类型的同时优雅地强制执行约束
- javascript - 右边的overflow-x位置