本文介绍了美丽的汤获得的第一个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能获得的第一个孩子?

How can I get the first child?

 <div class="cities">
       <div id="3232"> London </div>
       <div id="131"> York </div>
  </div>

我怎样才能得到伦敦?

How can I get London?

for div in nsoup.find_all(class_='cities'):
    print (div.children.contents)

AttributeError的:'的ListIterator'对象有没有属性'的内容

AttributeError: 'listiterator' object has no attribute 'contents'

推荐答案

div.children返回迭代器。

div.children returns an iterator.

for div in nsoup.find_all(class_='cities'):
    for childdiv in div.find_all('div'):
        print (childdiv.string) #london, york

AttributeError的升高,因为像的'\\ n'无标签,。孩子。只要使用适当的儿童选择器来查找特定的div。

AttributeError was raised, because of non-tags like '\n' are in .children. just use proper child selector to find the specific div.

(更多编辑)无法重现你的异常 - 这里就是我所做的:

(more edit) can't reproduce your exceptions - here's what I've done:

In [137]: print foo.prettify()
<div class="cities">
 <div id="3232">
  London
 </div>
 <div id="131">
  York
 </div>
</div>

In [138]: for div in foo.find_all(class_ = 'cities'):
   .....:     for childdiv in div.find_all('div'):
   .....:         print childdiv.string
   .....:
 London
 York

In [139]: for div in foo.find_all(class_ = 'cities'):
   .....:     for childdiv in div.find_all('div'):
   .....:         print childdiv.string, childdiv['id']
   .....:
 London  3232
 York  131

这篇关于美丽的汤获得的第一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:05