当前位置:网站首页>16 `bs对象.节点名div.属性contents` children descendants 获取子节点 子孙节点
16 `bs对象.节点名div.属性contents` children descendants 获取子节点 子孙节点
2022-06-28 21:21:00 【安迪python学习笔记】
16 bs对象.节点名div.属性contents children descendants 获取子节点 子孙节点
文章目录
1. 关联选择
<p>本是青灯不归客</p><p>却因浊酒留风尘</p><p>终是庄周梦了蝶</p><p>你是恩赐也是劫</p>
上述HTML代码有4个p节点,我们之前的节点选择方法只能选取到第一个p节点。
要选取第2、3、4p节点,我们就需要利用关联选择方法。

2. bs对象.节点名.属性contents 获取子节点
contents [kənˈtents]:内容。
语法格式:bs对象.节点名.contents
返回值:列表
取值方法:列表[索引]
# 声明一个html_str字符串变量,存储部分HTML代码
html_str = """ <html> <head><meta charset="utf-8"><title>古诗2首</title></head> <body> <div class="poems" id="section1"><h2>如梦令</h2><h3>李清照<span>(宋)</span></h3><p>试问卷帘人</p><p>却道海棠依旧</p><p>知否?知否?</p><p>应是绿肥红瘦</p></div> <div class="poems" id="section2"><h2>无题</h2><h3>佚名</h3> <p>本是青灯不归客</p><p>却因浊酒留风尘</p><p>终是庄周梦了蝶</p><p>你是恩赐也是劫</p> </div> </body> </html> """
# 1. 从bs4解析库导入BeautifulSoup类用于解析数据
from bs4 import BeautifulSoup
# 2.1 BeautifulSoup类(要解析的字符串,解析器)
# 2.2 传入2个参数,实例化类得到一个BeautifulSoup对象
bs_duixiang = BeautifulSoup(html_str, 'lxml')
print("步骤1:bs对象.节点名div——获取第1个div节点:")
print(bs_duixiang.div,'\n')
print("步骤2.1:bs对象.节点名div.属性contents——获取第1个div节点的所有子节点:")
print(bs_duixiang.div.contents,'\n')
print("步骤2.2 :属性contents得到的子节点的数据类型为列表:")
print(type(bs_duixiang.div.contents),'\n')
print("步骤3:用列表[索引]——取值:",'\n')
print("div节点的第1个子节点:",bs_duixiang.div.contents[0],'\n')
print("div节点的第2个子节点:",bs_duixiang.div.contents[1],'\n')
print("div节点的第5个子节点:",bs_duixiang.div.contents[4],'\n')
print("div节点的第5个子节点的文本内容:",bs_duixiang.div.contents[4].string,'\n')
【终端输出】
步骤1:bs对象.节点名div——获取第1个div节点:
<div class="poems" id="section1"><h2>如梦令</h2><h3>李清照<span>(宋)</span></h3><p>试问卷帘人</p><p>却道海棠依旧</p><p>知否?知否?</p><p>应是绿肥红瘦</p></div>
步骤2.1:bs对象.节点名div.属性contents——获取第1个div节点的所有子节点:
[<h2>如梦令</h2>, <h3>李清照<span>(宋)</span></h3>, <p>试问卷帘人</p>, <p>却道海棠依旧</p>, <p>知否?知否?</p>, <p>应是绿肥红瘦</p>]
步骤2.2 :属性contents得到的子节点的数据类型为列表:
<class 'list'>
步骤3:用列表[索引]——取值:
div节点的第1个子节点: <h2>如梦令</h2>
div节点的第2个子节点: <h3>李清照<span>(宋)</span></h3>
div节点的第5个子节点: <p>知否?知否?</p>
div节点的第5个子节点的文本内容: 知否?知否?
3. bs对象.节点名.children 获取子节点
children[ˈtʃɪldrən]:孩子们。
语法格式:bs对象.节点名.children
返回值:列表迭代器。
取值方法:用for循环从列表迭代器中取值。for i,child in enumerate(bs对象.节点名.children)
# 声明一个html_str字符串变量,存储部分HTML代码
html_str = """ <html> <head><meta charset="utf-8"><title>古诗2首</title></head> <body> <div class="poems" id="section1"><h2>如梦令</h2><h3>李清照<span>(宋)</span></h3><p>试问卷帘人</p><p>却道海棠依旧</p><p>知否?知否?</p><p>应是绿肥红瘦</p></div> <div class="poems" id="section2"><h2>无题</h2><h3>佚名</h3> <p>本是青灯不归客</p><p>却因浊酒留风尘</p><p>终是庄周梦了蝶</p><p>你是恩赐也是劫</p> </div> </body> </html> """
# 1. 从bs4解析库导入BeautifulSoup类用于解析数据
from bs4 import BeautifulSoup
# 2.1 BeautifulSoup类(要解析的字符串,解析器)
# 2.2 传入2个参数,实例化类得到一个BeautifulSoup对象
bs_duixiang = BeautifulSoup(html_str, 'lxml')
print("步骤1:bs对象.节点名div——获取第1个div节点:")
print(bs_duixiang.div,'\n')
print("步骤2.1:bs对象.节点名div.属性children——获取第1个div节点的所有子节点:")
print(bs_duixiang.div.children,'\n')
print("步骤2.2 :属性children得到的子节点的数据类型为列表迭代器:")
print(type(bs_duixiang.div.children),'\n')
print("步骤3.1:用for循环从列表迭代器中取值:")
for i,child in enumerate(bs_duixiang.div.children) :
print(i, child)
# '\n'的作用是输出一个空行,目的是为让输出内容美观,方便查看
print('\n')
print("步骤3.2 从列表迭代器中取出的child的数据类型为tag对象:")
print(type(child),'\n')
print("步骤4:输出第1个div节点最后一个子节点的文本内容:")
print(child.string,'\n')
【终端输出】
步骤1:bs对象.节点名div——获取第1个div节点:
<div class="poems" id="section1"><h2>如梦令</h2><h3>李清照<span>(宋)</span></h3><p>试问卷帘人</p><p>却道海棠依旧</p><p>知否?知否?</p><p>应是绿肥红瘦</p></div>
步骤2.1:bs对象.节点名div.属性children——获取第1个div节点的所有子节点:
<list_iterator object at 0x0000012FAE97B160>
步骤2.2 :属性children得到的子节点的数据类型为列表迭代器:
<class 'list_iterator'>
步骤3.1:用for循环从列表迭代器中取值:
0 <h2>如梦令</h2>
1 <h3>李清照<span>(宋)</span></h3>
2 <p>试问卷帘人</p>
3 <p>却道海棠依旧</p>
4 <p>知否?知否?</p>
5 <p>应是绿肥红瘦</p>
步骤3.2 从列表迭代器中取出的child的数据类型为tag对象:
<class 'bs4.element.Tag'>
步骤4:输出第1个div节点最后一个子节点的文本内容:
应是绿肥红瘦
for i,child in enumerate(bs_duixiang.div.children) 中enumerate的用法参考相关笔记。
4. bs对象.节点名.descendants 获取子孙节点
descendants [dɪˈsendənts]:后代。
generator [ˈdʒenəreɪtə]:生成器。
语法格式:bs对象.节点名.descendants
返回值:生成器。
取值方法:用for循环从生成器中取值。for i,child in enumerate(bs对象.节点名.descendants)
# 声明一个html_str字符串变量,存储部分HTML代码
html_str = """ <html> <head><meta charset="utf-8"><title>古诗2首</title></head> <body> <div class="poems" id="section1"><h2>如梦令</h2><h3>李清照<span>(宋)</span></h3><p>试问卷帘人</p><p>却道海棠依旧</p><p>知否?知否?</p><p>应是绿肥红瘦</p></div> <div class="poems" id="section2"><h2>无题</h2><h3>佚名</h3> <p>本是青灯不归客</p><p>却因浊酒留风尘</p><p>终是庄周梦了蝶</p><p>你是恩赐也是劫</p> </div> </body> </html> """
# 1. 从bs4解析库导入BeautifulSoup类用于解析数据
from bs4 import BeautifulSoup
# 2.1 BeautifulSoup类(要解析的字符串,解析器)
# 2.2 传入2个参数,实例化类得到一个BeautifulSoup对象
bs_duixiang = BeautifulSoup(html_str, 'lxml')
print("步骤1:bs对象.节点名div——获取第1个div节点:")
print(bs_duixiang.div,'\n')
print("步骤2.1:bs对象.节点名div.属性descendants—获取第1个div节点的所有子孙节点:")
print(bs_duixiang.div.descendants,'\n')
print("步骤2.2 :属性descendants得到的子孙节点的数据类型为生成器:")
print(type(bs_duixiang.div.descendants),'\n')
print("步骤3:用for循环从生成器中取值:")
for i, desc in enumerate(bs_duixiang.div.descendants) :
print(i, desc )
【终端输出】
步骤1:bs对象.节点名div——获取第1个div节点:
<div class="poems" id="section1"><h2>如梦令</h2><h3>李清照<span>(宋)</span></h3><p>试问卷帘人</p><p>却道海棠依旧</p><p>知否?知否?</p><p>应是绿肥红瘦</p></div>
步骤2.1:bs对象.节点名div.属性descendants—获取第1个div节点的所有子孙节点:
<generator object Tag.descendants at 0x0000012FAE8F0200>
步骤2.2 :属性descendants得到的子孙节点的数据类型为生成器:
<class 'generator'>
步骤3:用for循环从生成器中取值:
0 <h2>如梦令</h2>
1 如梦令
2 <h3>李清照<span>(宋)</span></h3>
3 李清照
4 <span>(宋)</span>
5 (宋)
6 <p>试问卷帘人</p>
7 试问卷帘人
8 <p>却道海棠依旧</p>
9 却道海棠依旧
10 <p>知否?知否?</p>
11 知否?知否?
12 <p>应是绿肥红瘦</p>
13 应是绿肥红瘦
边栏推荐
- 题解 Ananagrams(UVa156)紫书P113map的应用
- Application practice | 1billion data second level correlation. Huolala's OLAP System Evolution Based on Apache Doris (with PPT download)
- Leetcode56. consolidation interval
- Bitbucket 使用 SSH 拉取仓库失败的问题
- 券商公司开户哪个最靠谱最安全呢
- Leetcode daily question - Sword finger offer II 091 Paint the house
- No module named ‘PyEMD‘ ; Use plt figure()TypeError: ‘module‘ object is not callable
- LeetCode117. Populate the next right node pointer for each node_ II
- LeetCode123. 买卖股票的最佳时机III
- LeetCode226. Flip binary tree
猜你喜欢

On the complexity of software development and the way to improve its efficiency

我也差点“跑路”

How to analyze the relationship between enterprise digital transformation and data asset management?

力扣树的进一步应用
![[try to hack] cobalt strike (I)](/img/2b/5d274078b7d7ebd05b7c6d9e020868.png)
[try to hack] cobalt strike (I)

with torch. no_ Grad(): reason for using

Figure neural network can also be used as CV backbone model. Huawei Noah Vig architecture is comparable to CNN and transformer

How do I download videos? Look at the super simple method!

Mongodb - replica set and sharding

API 网关 Apache APISIX 助力雪球双活架构演进
随机推荐
Leetcode: merge two ordered linked lists_ twenty-one
APISIX 助力中东社交软件,实现本地化部署
MongoDB——副本集与分片
Explanation and usage of sqrt() function
LeetCode123. The best time to buy and sell stocks III
Web自动化工具选择
LeetCode121. 买卖股票的最佳时机
Bitbucket 使用 SSH 拉取仓库失败的问题
LeetCode每日一题——515. 在每个树行中找最大值
Leetcode: merge K ascending linked lists_ twenty-three
Leetcode daily question - 522 Longest special sequence II
GlobalSign的泛域名SSL证书
pyechart绘制多条y轴折线图
图神经网络也能用作CV骨干模型,华为诺亚ViG架构媲美CNN、Transformer
Biovendor free light chain( κ and λ) Test steps of ELISA Kit
LeetCode188. 买卖股票的最佳时机IV
力扣树的进一步应用
Leetcode: expand a binary tree into a linked list_ one hundred and fourteen
No module named ‘PyEMD‘ ; Use plt figure()TypeError: ‘module‘ object is not callable
Leetcode daily question - 710 Random numbers in the blacklist