昨天看书,没有用enumurate枚举的时候,直接print,完全发觉不了他们的区别,倍感困惑。
子标签和后代标签:  .children 和 .descendants

今天看了其他人写的教程,用了枚举法,终于,终于,发现它们之间的区别啦!敲锣打鼓,掌声响起来
子标签和后代标签:  .children 和 .descendants

还要注意,子代接下一个子代时,可能是换行符,看下面children找出的子代,你就可以体会到啦!
descendants是找了子标签,然后再一步步探入别人的家中,把一个个后代,按辈分由大往小找着。

下面以这段html作为栗子:
子标签和后代标签:  .children 和 .descendants

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

1.说说我们的 .children

输入:

from bs4 import BeautifulSoup

soup1 = BeautifulSoup(html, 'lxml')
print(soup1.p.children)
for i, child in enumerate(soup1.p.children):
    print(i, child)

输出:

<list_iterator object at 0x000000DD59609898>
0 
            Once upon a time there were three little sisters; and their names were
            
1 <a class="sister" href="http://example.com/elsie" >
<span>Elsie</span>
</a>
2 

3 <a class="sister" href="http://example.com/lacie" >Lacie</a>
4  
            and
            
5 <a class="sister" href="http://example.com/tillie" >Tillie</a>
6 
            and they lived at the bottom of a well.

2.说说我们的 .descendants

输入:

from bs4 import BeautifulSoup

soup2 = BeautifulSoup(html, 'lxml')
print(soup2.p.children)
for i, desc in enumerate(soup2.p.descendants):
    print(i, desc)

输出:

<list_iterator object at 0x000000DD595897B8>
0 
            Once upon a time there were three little sisters; and their names were
            
1 <a class="sister" href="http://example.com/elsie" >
<span>Elsie</span>
</a>
2 

3 <span>Elsie</span>
4 Elsie
5 

6 

7 <a class="sister" href="http://example.com/lacie" >Lacie</a>
8 Lacie
9  
            and
            
10 <a class="sister" href="http://example.com/tillie" >Tillie</a>
11 Tillie
12 
            and they lived at the bottom of a well.

形象点说,就是假设现在小区里要调查房屋入住情况。
.children呢,找出每一户,登记一下有没人住,就完事了。
而 .descendants呢,就不一样了。登记完每一户的入住情况后,还要登记每间房的入住情况,
每间房分别住了谁,兴趣、职业、爱好、户口所在地……
子标签和后代标签:  .children 和 .descendants

势必把你查清查楚。
哎呀,妈呀,好可怕!
子标签和后代标签:  .children 和 .descendants

这就是他们的区别了

最近天气热到爆炸,老天可否大发慈悲一回?
子标签和后代标签:  .children 和 .descendants
我要融化了
化了

相关文章:

  • 2022-12-23
  • 2021-08-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-02
  • 2021-11-17
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
  • 2021-07-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案