这是一个例子:
<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/