0

I want to add a line with HTML tag using beautifulsoup.

Input:

<tr>
    <td>Hi </td>
    <td>Hello</td>
    <td>World</td>
</tr>

Output:I want to add the 4th line which is Good Morning in seperate tag

<tr>
    <td>Hi </td>
    <td>Hello</td>
<!--<td>World</br>Good Morning</td> -->
    <td></br>Good Morning</td> 

</tr>

I made the comment using replacewith function, now i'm stuck with adding new line. please help me on this.

petezurich
  • 9,280
  • 9
  • 43
  • 57
mukesh tech01
  • 69
  • 1
  • 8
  • So you want `world` to be replaced by `Good Morning` this right? – KunduK Jan 14 '20 at 12:31
  • yes ,is there anyway to do it , please help me on this – mukesh tech01 Jan 14 '20 at 12:35
  • Try researching and writing some code yourself before asking for help. Look at [this](https://stackoverflow.com/questions/21356014/how-can-i-insert-a-new-tag-into-a-beautifulsoup-object) and [this](https://stackoverflow.com/questions/5598524/can-i-remove-script-tags-with-beautifulsoup) post to start. – Joseph Rajchwald Jan 14 '20 at 12:39
  • @Joseph , I tried many ways like insert , insert_after but most of them are at soup level and the examples are one line but the above code which td at nested level i didnt find good example..FYI i was trying from past 2 hours – mukesh tech01 Jan 14 '20 at 12:50
  • Does this answer your question? [Using python/BeautifulSoup to replace HTML tag pair with a different one](https://stackoverflow.com/questions/15545594/using-python-beautifulsoup-to-replace-html-tag-pair-with-a-different-one) – Tijmen Jan 14 '20 at 12:57
  • No Tijmen , I want to change the text within html tag – mukesh tech01 Jan 14 '20 at 13:09

1 Answers1

1

First find the element and then next_element which is text and then replace with your text.

from bs4 import BeautifulSoup

html='''<tr>
    <td>Hi </td>
    <td>Hello</td>
    <td>World</td>
</tr>'''

soup=BeautifulSoup(html,'html.parser')
soup.find('td',text='World').next_element.replace_with("</br>Good Morning")
print(soup.prettify(formatter=None))

Output:

<tr>
 <td>
  Hi
 </td>
 <td>
  Hello
 </td>
 <td>
  </br>Good Morning
 </td>
</tr>
KunduK
  • 32,888
  • 5
  • 17
  • 41
  • Thanks for your response , actually i have xml document within it i have small part of above code.i read it as lxml document now i guess i cant read it as htmll parser – mukesh tech01 Jan 14 '20 at 13:25
  • @mukeshtech01 : does this solution helps to problem? – KunduK Jan 14 '20 at 13:29