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

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 class="wrapped">
<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 class="auto-cursor-target">
<br/>
</p>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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>

EDIT: If you want to insert arbitrary HTML code, you can try:

what_to_insert = BeautifulSoup(
    '<tr param="xxx">This is new <b>text</b></tr>', "html.parser"
)

row.insert_after(what_to_insert)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x