Beautifulsoup显示重复

时间:2014-12-22 16:05:43

标签: python html beautifulsoup

所以基本上我是Beautifulsoup的新手,我的最终目标是将一些html放在JSON字典的字段中,Key是HTML标签,dict的值是HTML内容。

由于我不知道我将接收什么HTML,所以我必须让它变得动态。

在我的测试中,当我尝试创建我提到的字典时,我得到了一些重复的输出。

基本上我有:

from bs4 import BeautifulSoup

if self.description:
    print "original: ", self.description

    soup = BeautifulSoup(self.description)
    print "changed: "

    for tag in soup.find_all(True): # find all tag
        print tag

输出:

original:  
<p><strong>My name is james bond</strong></p>
<p><strong>​007</strong></p>

changed: 
<p><strong>My name is james bond</strong></p>
<strong>My name is james bond</strong>
<p><strong>​007</strong></p>
<strong>​007</strong>

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您正在循环所有标记。由于HTML是嵌套的树结构,这意味着您将多次看到标签;首先作为标签的孩子,然后是标签本身。例如,<strong>​007</strong>嵌套在<p>标记内,因此它首先显示在那里。

如果你不想这样做,你将不得不循环遍历一个级别的标签

for tag in soup.body or soup:  # prefer the body tag if exists
    print tag

演示:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <p><strong>My name is james bond</strong></p>
... <p><strong>007</strong></p>
... ''')
>>> soup.body
<body><p><strong>My name is james bond</strong></p>
<p><strong>007</strong></p>
</body>
>>> for tag in soup.body or soup:  # prefer the body tag if exists
...     print tag
... 
<p><strong>My name is james bond</strong></p>


<p><strong>007</strong></p>