所以基本上我是 Beautifulsoup 的新手,我的最终目标是将一些 html 放入 JSON 字典的字段中,其中键是 HTML 标签,字典的值是 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>
我怎样才能实现这个目标?
最佳答案
您正在循环访问所有标签。由于 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>
关于python - Beautifulsoup 显示重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606202/