bs4模块使用(二)

遍历文档树

怎样从文档的一段内容找到另一段内容?

html_doc = """
<html><head><title>The Dormouse's story</title></head>
    <body>
<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 href="http://example.com/elsie" class="sister" id="link1">Elsie</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
soup = BeautifulSoup(html_doc, 'html.parser')

子节点

一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点

tag名字

想要获取节点,最简单的方法就是提供tag名字,甚至可以在文档树的tag中多次调用这个方法

通过点取属性的方式只能获得当前名字的第一个tag,后面会介绍获取全部

print(soup.head)
print(soup.title)
print(soup.body.p)
.contents和.children
  • .contents
    .contents 属性可以将tag的子节点以列表的方式输出
  • .children
    通过tag的 .children 生成器,可以对tag的子节点进行循环

print(soup.body.contents)

for item in soup.body.children:
    print(item)

字符串没有子节点
.contents和.children属性获取的子节点,仅包含tag的直接子节点

.descendants

.descendants属性,不仅可以获取直接子节点,子孙节点也可以获取

html_doc = """<html><head><title>The Dormouse's story</title></head><body><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 href="http://example.com/elsie" class="sister" id="link1">Elsie</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>"""

soup = BeautifulSoup(html_doc,features="lxml")

 
for item in soup.body.descendants:
    print(item)

print("--------------")
for item in soup.body.contents:
    print(item)
print("--------------")

for item in soup.body.children:
    print(item)

在这里插入图片描述

使用该属性,不需要对直接子节点的子节点进行二次数据提取

.string
  • tag只有一个NavigableString类型的子节点,可以使用.string得到子节点
  • tag仅有一个子节点,那么tag调用.string属性,输出结果和上述一致

如果tag中存在多个字符串,可以用.strings来循环获取,如果存在很多空格或空行,可以通过.stripped_strings去除多余空白内容

全部是空格的行会被忽略掉,段首和段末的空白会被删除

父节点

每个tag或字符串都有父节点:被包含在某个tag中

.parent

通过 .parent 属性来获取某个元素的父节点

.parents

通过元素的.parents属性可以递归得到元素的所有父辈节点

兄弟节点

是同一个元素的子节点,可以被称为兄弟节点

.next_sibling和.previous_sibling

首个子节点无.previous_sibling,最后一个子节点无.next_sibling属性,这两个用于获取兄弟节点

通过 .next_siblings 和 .previous_siblings 属性可以对当前节点的兄弟节点迭代输出

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卫生纸不够用

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值