How to find children of nodes using BeautifulSoup

tej.tan picture tej.tan · Jun 9, 2011 · Viewed 188.8k times · Source

I want to get all the <a> tags which are children of <li>:

<div>
<li class="test">
    <a>link1</a>
    <ul> 
       <li>  
          <a>link2</a> 
       </li>
    </ul>
</li>
</div>

I know how to find element with particular class like this:

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

But I don't know how to find all <a> which are children of <li class=test> but not any others.

Like I want to select:

<a>link1</a>

Answer

cerberos picture cerberos · Jun 9, 2011

Try this

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