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 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
children
is a sequence of children, each one of which hascontents
. The sequence itself doesn't havecontents
. It's just like[1, 2, 3]
isn't an integer. Meanwhile, like any sequence, to get the first value, you can justnext(iter(div.children))
.