如何使用 BeautifulSoup 查找节点的子节点 [英] How to find children of nodes using BeautifulSoup

查看:44
本文介绍了如何使用 BeautifulSoup 查找节点的子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得所有 标签,它们是

  • 的子标签:

  • <a>link1</a><ul><li><a>link2</a>
  • 我知道如何找到具有特定类的元素,如下所示:

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

    但我不知道如何找到所有 <a>,它们是 <li class=test> 的孩子,而不是任何其他孩子.

    就像我想选择的一样:

    link1

    解决方案

    试试这个

    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)
    

    这篇关于如何使用 BeautifulSoup 查找节点的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆