22

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'

1
  • 1
    children is a sequence of children, each one of which has contents. The sequence itself doesn't have contents. It's just like [1, 2, 3] isn't an integer. Meanwhile, like any sequence, to get the first value, you can just next(iter(div.children)).
    – abarnert
    Mar 19, 2013 at 4:06

3 Answers 3

15

With modern versions of bs4 (certainly bs4 4.7.1+) you have access to :first-child css pseudo selector. Nice and descriptive. Use soup.select_one if you only want to return the first match i.e. soup.select_one('.cities div:first-child').text. It is considered good practice to test is not None before using .text accessor.

from bs4 import BeautifulSoup as bs

html = '''
<div class="cities"> 
       <div id="3232"> London </div>
       <div id="131"> York </div>
  </div>
  '''
soup = bs(html, 'lxml') #or 'html.parser'
first_children = [i.text for i in soup.select('.cities div:first-child')]
print(first_children)
2
  • How did you know the correct syntax for the css selector? I could not easily find how to make a css selector that selects the first child of a parent element with a certain class. My initial guess was that it would be element.class:first-child as element.class is used to select an element by class. And w3 Schools and MDN Web Docs don't suggest how to do this. Mar 20 at 19:46
  • 1
14

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
3
  • AttributeError: 'NavigableString' object has no attribute 'contents', and when I use string instead of contents it gives RuntimeError: maximum recursion depth exceeded while calling a Python object
    – Emmet B
    Mar 19, 2013 at 3:05
  • It prints None, None then RuntimeError: maximum recursion depth exceeded while calling a Python object
    – Emmet B
    Mar 19, 2013 at 3:14
  • 2
    by div['id'] or like div.get('id', None). same as if you would retrieve something from a dict
    – thkang
    Mar 19, 2013 at 3:19
8

The current accepted answer gets all cities, when the question only wanted the first.

If you only need the first child, you can take advantage of .children returning an iterator and not a list. Remember that an iterator generates list items on the fly, and because we only need the first element of the iterator, we don't ever need to generate all other city elements (thus saving time).

for div in nsoup.find_all(class_='cities'):
    first_child = next(div.children, None)
    if first_child is not None:
        print(first_child.string.strip())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.