且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 BeautifulSoup 查找节点的子节点

更新时间:2023-02-05 20:39:46

试试这个

li = soup.find('li', {'class': 'text'})children = li.findChildren("a", recursive=False)对于儿童中的儿童:打印(孩子)

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>

Try this

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