Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a new row to html file by using python beautifulesoup

I am using python 2.7, beautifulsoup. I have a local html file and I want to insert information in a table by appending new rows to it.

After searching from web, I am able to pick the correct table which is no id.

import requests
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('./result.html'), 'html.parser')

table = soup.find(text="Beta").find_parent("table")
for row in table.find_all("tr")[1:]:
    print([cell.get_text(strip=True) for cell in row.find_all("td")])

Here is what I want to do. Before:

<tr><td colspan="3"><hr></td></tr>
<tr><td>Beta</td><td>0.0883</td><td>-</td></tr>
<tr><td>Alpha</td><td>0.1115</td><td>-</td></tr>
</tbody>
</table>

After:

<tr><td colspan="3"><hr></td></tr>
<tr><td>Beta</td><td>0.0883</td><td>-</td></tr>
<tr><td>Alpha</td><td>0.1115</td><td>-</td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><td>Total Trade</td><td>2574</td><td>-</td></tr>
</tbody>
</table>

Thank you very much.

like image 579
sflee Avatar asked Oct 25 '25 05:10

sflee


1 Answers

new_tag = soup.new_tag("Your Tag") #add even more tags as needed
new_tag.append("Your Text")
# insert the new tag after the last tag using insert_after
the_last_tag_i_want_to_insert_after.insert_after(new_tag)
like image 72
TheLazyScripter Avatar answered Oct 27 '25 18:10

TheLazyScripter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!