Python 在特定表行上方插入元素
我正在使用Beautifulsoup4,希望找到一个特定的表行,并在上面插入一个行元素 以html为例:Python 在特定表行上方插入元素,python,python-3.x,beautifulsoup,Python,Python 3.x,Beautifulsoup,我正在使用Beautifulsoup4,希望找到一个特定的表行,并在上面插入一个行元素 以html为例: <table> <tr> <td> <p> <span>Sample Text</span> </p> </td> </tr> </table> 但看起来并不健壮。有没有更干净的方法的建议 使用参数定位文本“示例文本” 使用查找上一个 用于将新元素添加到汤中 从bs4导
<table>
<tr>
<td>
<p>
<span>Sample Text</span>
</p>
</td>
</tr>
</table>
但看起来并不健壮。有没有更干净的方法的建议
汤中
从bs4导入美化组
html=”“”
示例文本
"""
soup=BeautifulSoup(html,“html.parser”)
对于soup.find中的标记(“span”,text=“示例文本”):
标记。查找以前的(“tr”)。在之前插入(“我的新标记”)
打印(soup.prettify())
输出:
<table>
MY NEW TAG
<tr>
<td>
<p>
<span>
Sample Text
</span>
</p>
</td>
</tr>
</table>
我的新标签
示例文本
很好的解决方案!!
from bs4 import BeautifulSoup
html = """
<table>
<tr>
<td>
<p>
<span>Sample Text</span>
</p>
</td>
</tr>
</table>
"""
soup = BeautifulSoup(html, "html.parser")
for tag in soup.find("span", text="Sample Text"):
tag.find_previous("tr").insert_before("MY NEW TAG")
print(soup.prettify())
<table>
MY NEW TAG
<tr>
<td>
<p>
<span>
Sample Text
</span>
</p>
</td>
</tr>
</table>