Beautiful soup getting the first child

前端 未结 3 1852
深忆病人
深忆病人 2021-01-17 09:31

How can I get the first child?

 
London
York
3条回答
  •  日久生厌
    2021-01-17 09:53

    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()
    
    London
    York
    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

提交回复
热议问题