Home > OS >  Trying to append a new row to the first row in a the table body with BeautifulSoup
Trying to append a new row to the first row in a the table body with BeautifulSoup

Time:05-01

Having trouble appending a new row to the first row (the header row) in the table body ().

my code:

from bs4 import BeautifulSoup  

soup = BeautifulSoup(open('page_content.xml'), 'html.parser')

# append a row to the first row in the table body
row = soup.find('tbody').find('tr')
row.append(soup.new_tag('tr', text='New Cell'))

print(row)

the output:

<tr>
<th>Version</th>
<th>Jira</th>
<th colspan="1">Date/Time</th>
<tr text="New Cell"></tr></tr>

what the output should be:

<tr>
<th>Version</th>
<th>Jira</th>
<th colspan="1">Date/Time</th>
</tr>
<tr text="New Cell"></tr>

the full xml file is:

<h1>Rental Agreement/Editor</h1>
<table >
<colgroup>
<col/>
<col/>
<col/>
</colgroup>
<tbody>
<tr>
<th>Version</th>
<th>Jira</th>
<th colspan="1">Date/Time</th>
<tr text="New Cell"></tr></tr>
<tr>
<td>1.0.1-0</td>
<td>ABC-1234</td>
<td colspan="1">
<br/>
</td>
</tr>
</tbody>
</table>
<p >
<br/>
</p>

CodePudding user response:

You can use .insert_after:

from bs4 import BeautifulSoup

html_doc = """
<table>
<tr>
<th>Version</th>
<th>Jira</th>
<th colspan="1">Date/Time</th>
</tr>

<tr>
<td> something else </td>
</tr>
</table>
"""

soup = BeautifulSoup(html_doc, "html.parser")

row = soup.select_one("tr:has(th)")
row.insert_after(soup.new_tag("tr", text="New Cell"))

print(soup.prettify())

Prints:

<table>
 <tr>
  <th>
   Version
  </th>
  <th>
   Jira
  </th>
  <th colspan="1">
   Date/Time
  </th>
 </tr>
 <tr text="New Cell">
 </tr>
 <tr>
  <td>
   something else
  </td>
 </tr>
</table>
  • Related