在Beautiful Soup中添加文本到p标签

ill*_*ger 3 html python xml beautifulsoup

我想知道是否有人知道如何向标签添加文本(p,b - 您可能想要包含字符数据的任何标签).文档中没有提到你如何做到这一点.

swa*_*son 5

我不确定这是不是你想要的,但也许这是一个开始......

from BeautifulSoup import BeautifulSoup, NavigableString

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

输出

<p>new</p>
Run Code Online (Sandbox Code Playgroud)

文档显示了一些类似的例子:http://www.crummy.com/software/BeautifulSoup/documentation.html#Modifying%20the%20Parse%20Tree