开发者

Adding text to p tag in Beautiful Soup

开发者 https://www.devze.com 2022-12-20 23:34 出处:网络
I was wondering if anyone knew how to add text to a tag (p, b -- any开发者_如何学JAVA tag where you might want to include character data). The documentation mentions no where how you might do this. I\

I was wondering if anyone knew how to add text to a tag (p, b -- any开发者_如何学JAVA tag where you might want to include character data). The documentation mentions no where how you might do this.


I'm not sure exactly if this is what you want, but maybe it's a start...

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 documentations shows a few more similar examples: http://www.crummy.com/software/BeautifulSoup/documentation.html#Modifying%20the%20Parse%20Tree


>>> 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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号