Beautiful soup getting the first child
beautifulsoup, python
Solution
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
Problem
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' object has no attribute 'contents'