python - Beautifulsoup 显示重复项

标签 python html beautifulsoup

所以基本上我是 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/

相关文章:

python - Odoo 自动操作无法运行或工作

python - 从 cygwin 交互运行 win32 ipython 二进制文件

python - Pandas 替换(删除)字符串中的不同字符

html - 如何显示此HTML输出:使用XSLT ..的1 + 3 + 4 + 17 + 8 + 15 = 48?

python - 获取与<li>标签相关的<h2>标签

python - 无法按位置或属性匹配时在 BeautifulSoup 中提取标签值

python - 导入错误: cannot import name 'IncompleteRead' - Windows

javascript - 模板内的按钮从不调用处理程序

javascript - 需要对我的幻灯片代码进行一些修改

python - 优化我的 Python Scraper