insert element above specific table row beautifulsoup python

Viewed 197

I'm working with BeautifulSoup 4 and want to find a specific table row and insert a row element above it.

Take the html as a sample:

<table>
<tr>
<td>
<p>
<span>Sample Text</span>
</p>
</td>
</tr>
</table>

There are many more tables in the document, but this is a typical structure. The tables do make use of names or ids and cannot be modified.

My goal is to locate "Sample Text", find that tr in which it belongs and set focus to it so that I can dynamically insert a new table row directly above it.

I've tried something like in order to capture the top root table row:

for elm in index(text='Sample Text'):
     elm.parent.parent.parent.parent

Doesn't seem robust though. Any suggestions for a cleaner approach?

1 Answers
  1. locate the text "Sample Text" using the text= argument.
  2. Find the previous <tr> using find_previous().
  3. Use insert_before() to add a new element to the soup.

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

Output:

<table>
 MY NEW TAG
 <tr>
  <td>
   <p>
    <span>
     Sample Text
    </span>
   </p>
  </td>
 </tr>
</table>
Related