The Python Oracle

How to find children of nodes using BeautifulSoup

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Question
00:46 Accepted answer (Score 204)
00:59 Answer 2 (Score 147)
01:30 Answer 3 (Score 22)
01:42 Answer 4 (Score 16)
02:07 Thank you

--

Full question
https://stackoverflow.com/questions/6287...

Answer 1 links:
https://www.crummy.com/software/Beautifu...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #html #beautifulsoup

#avk47



ACCEPTED ANSWER

Score 220


Try this

li = soup.find('li', {'class': 'test'})
children = li.findChildren("a" , recursive=False)
for child in children:
    print(child)



ANSWER 2

Score 150


There's a super small section in the DOCs that shows how to find/find_all direct children.

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-recursive-argument

In your case as you want link1 which is first direct child:

# for only first direct child
soup.find("li", { "class" : "test" }).find("a", recursive=False)

If you want all direct children:

# for all direct children
soup.find("li", { "class" : "test" }).findAll("a", recursive=False)



ANSWER 3

Score 24


Perhaps you want to do

soup.find("li", { "class" : "test" }).find('a')



ANSWER 4

Score 16


try this:

li = soup.find("li", { "class" : "test" })
children = li.find_all("a") # returns a list of all <a> children of li

other reminders:

The find method only gets the first occurring child element. The find_all method gets all descendant elements and are stored in a list.