Adding text to p tag in Beautiful Soup

I was wondering if anyone knows how to add text to a tag (p, b is any tag where you can include character data). The documentation does not mention where you can do this.

+3
source share
2 answers

I'm not sure what exactly you want, but maybe this is the beginning ...

from BeautifulSoup import BeautifulSoup, NavigableString

html = "<p></p>"
soup = BeautifulSoup(html)
ptag = soup.find('p')
ptag.insert(0, NavigableString("new"))
print ptag

Outputs

<p>new</p>

The docs show some more similar examples: http://www.crummy.com/software/BeautifulSoup/documentation.html#Modifying%20the%20Parse%20Tree

+4
source
>>> import BeautifulSoup
>>> b=BeautifulSoup.BeautifulSoup("<p></p><p></p>")
>>> for t,s in zip(b,[u'hello',u'world']):
...     t.contents.append(BeautifulSoup.NavigableString(s))
... 
>>> b
<p>hello</p><p>world</p>
+1
source

Source: https://habr.com/ru/post/1733288/


All Articles