Python : BeautifulSoup遍历文档树

遍历文档树
还拿”爱丽丝梦游仙境”的文档来做例子:

html_doc = “”"

The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.

...

"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
通过这段例子来演示怎样从文档的一段内容找到另一段内容

子节点
一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点.Beautiful Soup提供了许多操作和遍历子节点的属性.

注意: Beautiful Soup中字符串节点不支持这些属性,因为字符串没有子节点

tag的名字
操作文档树最简单的方法就是告诉它你想获取的tag的name.如果想获取 标签,只要用 soup.head :

soup.head

The Dormouse’s story

soup.title

The Dormouse’s story

这是个获取tag的小窍门,可以在文档树的tag中多次调用这个方法.下面的代码可以获取标签中的第一个标签:

soup.body.b

The Dormouse’s story

通过点取属性的方式只能获得当前名字的第一个tag:

soup.a

Elsie

如果想要得到所有的标签,或是通过名字得到比一个tag更多的内容的时候,就需要用到 Searching the tree 中描述的方法,比如: find_all()

soup.find_all(‘a’)

[Elsie,

Lacie,

Tillie]

.contents 和 .children
tag的 .contents 属性可以将tag的子节点以列表的方式输出:

head_tag = soup.head
head_tag

The Dormouse’s story

head_tag.contents
[The Dormouse’s story]

title_tag =

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值