python - 当组都在同一元素中时,使用 BeautifulSoup 将 HTML 分成组

标签 python html parsing beautifulsoup

这是一个例子:

<p class='animal'>cats</p>
<p class='attribute'>they meow</p>
<p class='attribute'>they have fur</p>
<p class='animal'>turtles</p>
<p class='attribute'>they don't make noises</p>
<p class='attribute'>they have shells</p>

如果每只动物都在一个单独的元素中,我可以迭代这些元素。那太好了。但是我尝试解析的网站将所有信息都集中在一个元素中。

将汤分成不同的动物,或者以其他方式提取属性和它们属于哪种动物的最佳方法是什么?

(欢迎推荐更好的标题)

最佳答案

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup("""
<p class='animal'>cats</p>
<p class='attribute'>they meow</p>
<p class='attribute'>they have fur</p>
<p class='animal'>turtles</p>
<p class='attribute'>they don't make noises</p>
<p class='attribute'>they have shells</p>
""")

animals = []
attributes = {}

for p in soup.findAll('p'):
    if (p['class'] == 'animal'):
        animals.append(p.string)
    elif (p['class'] == 'attribute'):
        if animals[-1] not in attributes.keys():
            attributes[animals[-1]] = [p.string]
        else:
            attributes[animals[-1]].append(p.string)

print animals
print attributes

这应该有效。

关于python - 当组都在同一元素中时,使用 BeautifulSoup 将 HTML 分成组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3124612/

相关文章:

python - 如何处理TypeError : __call__() takes at least 2 arguments (1 given)?

html - 如何在 CSS 中传递符号 &?

javascript - 缩放时如何绑定(bind)图像平移(HTML Canvas)

xml - 如何解析 Coldfusion 中的每个 XML 元素/XML 子元素

json - 在 Golang 中解析 JSON 时出错

java - Xtext运行时编译

python - 为什么 set().union(*list1) 给我一个列表中两个列表的并集?

python - MPICH2 和 mpi4y 之间的区别

python - Moongoose 和 dict 转换为数组失败

javascript - 检测何时加载图像列表