BeautifulSoup - Akses Children dan descendants



Pada contoh ini digunakan file html seperti berikut.

<html>
    <head>
        <title>
            The Dormouse's story
        </title>
    </head>
    <body>
        <b></b>
        <p class="title">
            <b>
                The Dormouse's story
            </b>
        </p>
        <p class="story">
            Once upon a time there were three little sisters; and their names were
            <a class="sister" href="http://example.com/elsie" id="link1">
                Elsie
            </a>
            ,
            <a class="sister" href="http://example.com/lacie" id="link2">
                Lacie
            </a>
                and
            <a class="sister" href="http://example.com/tillie" id="link2">
                Tillie
            </a>
                ; and they lived at the bottom of a well.
        </p>
        <p class="story">
            <b>
                The End
            </b>
        </p>
    </body>
</html>

Untuk mengetahui sebuah tag memiliki berapa children, gunakan property .contents yang akan mengembalikan objek list.

Kita juga bisa menggunakan property .children, returnya berupa objek list_iterator.

Note: yang dimaksud dengan children adalah tag html, bukan teks konten dari tag tersebut.

>>> from bs4 import BeautifulSoup
>>> html_doc = "diisi dengan file html diatas...."
>>> soup = BeautifulSoup(html_doc, 'lxml')
>>> print(soup.body.contents)
['\n', <p class="title"><b>The Dormouse's story</b></p>, '\n', <p class="story">
Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>, '\n', <p class="story">...</p>, '\n
']
>>> for child in soup.body.children:
...     print(child)
...


<p class="title"><b>The Dormouse's story</b></p>


<p class="story">Once upon a time there were three little sisters; and their names were
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
and they lived at the bottom of a well.
<p class="story">...</p>


Dalam contoh html, head memiliki 1 children, head. Sementara head juga memiliki children, dalam hal ini adalah teks "The Dormouse's Story". Untuk mengaksesnya menggunakan property descendants.

>>> for child in soup.head.descendants:
...     print(child)
...
The Dormouse's story
The Dormouse's story
BeautifulSoup - Akses Children dan descendants BeautifulSoup - Akses Children dan descendants Reviewed by noname needed on May 25, 2018 Rating: 5

No comments:

Powered by Blogger.