Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在特定表行上方插入元素_Python_Python 3.x_Beautifulsoup - Fatal编程技术网

Python 在特定表行上方插入元素

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导

我正在使用Beautifulsoup4,希望找到一个特定的表行,并在上面插入一个行元素

以html为例:

<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>