Beautiful soup getting the first child

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

How can I get the first child?

 
London
York
3条回答
  •  粉色の甜心
    2021-01-17 10:02

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

提交回复
热议问题