beautifulsoup finding all children under certain child

Viewed 52

so im basically trying to find the children of this ul but only the elements that are under a child

so if i have this html block

<ul>
    <li class = "list_item_1">item 1</li>
    <li class = "list_item_2">item 2</li>
    <li class = "list_item_3">item 3</li>
    <li class = "list_item_4">item 4</li>

</ul>

i want to grab the children below the second item using find_all

so i expect the output of the find_all to be

[<li class = "list_item_3">item 3</li> , <li class = "list_item_4">item 4</li>]
1 Answers

You can use .find_all(recursive=False) with list slice:

from bs4 import BeautifulSoup

html_doc = """
<ul>
    <li class = "list_item_1">item 1</li>
    <li class = "list_item_2">item 2</li>
    <li class = "list_item_3">item 3</li>
    <li class = "list_item_4">item 4</li>

</ul>
"""

soup = BeautifulSoup(html_doc, "html.parser")

print(soup.ul.find_all(recursive=False)[2:])

Prints:

[<li class="list_item_3">item 3</li>, <li class="list_item_4">item 4</li>]

Or if you're open to using .select, you can use CSS selector with ~:

print(soup.select(".list_item_2 ~ *"))

Prints:

[<li class="list_item_3">item 3</li>, <li class="list_item_4">item 4</li>]
Related