如何在beautifulsoup中只获得完整的li标签?

2024-10-04 05:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下几点

<ul class="fullname">
    <li><a href="">some name</a></li>
    <li>
        <ul>
            <li>name1</li>
            <li>Name2</li>
        </ul>
    </li>
        <ul>
            <li>name3</li>
            <li>Name4</li>
        </ul>
    </li>         
</ul>

我只想要三个元素,在第一个索引中,比如 <li><a href="">some name</a></li>和第二<ul><li>name1</li><li>Name2</li></ul>

我试过以下方法

navContent = content.find("li",{"class":"fullname"})
children = navContent.find_all("li")

但是在第二个索引中,它给出的是<li>name1</li>,而不是整个li。我怎样才能得到它?你知道吗


Tags: 方法name元素somelifindulclass
1条回答
网友
1楼 · 发布于 2024-10-04 05:31:04

使用^{}

根据文件:

If you call mytag.find_all(), Beautiful Soup will examine all the descendants of mytag: its children, its children’s children, and so on. If you only want Beautiful Soup to consider direct children, you can pass in recursive=False.

navContent = content.find("ul",{"class":"fullname"})
children = navContent.find_all("li", recursive=False)

相关问题 更多 >