子标签和后代标签: .children 和 .descendants

昨天看书,没有用enumurate枚举的时候,完全发觉不了他们的区别,倍感困惑。
今天看了其他人写的教程,用了枚举法,然后就发现他们之间的区别了。
还要注意,子代接下一个子代时,可能是换行符,看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" id="link1">
                <span>Elsie</span>
            </a>
            <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> 
            and
            <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
            and they lived at the bottom of a well.
        </p>
        <p class="story">...</p>
"""
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" id="link1">
<span>Elsie</span>
</a>
2 

3 <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
4  
            and
            
5 <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
6 
            and they lived at the bottom of a well.
        
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" id="link1">
<span>Elsie</span>
</a>
2 

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

6 

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

继续潜水,后期再来丰富吧,记录一下

转载于:https://www.cnblogs.com/wyy1480/p/11192153.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值