python+BeautifulSoup文档遍历树子节点

文档遍历树:

html_doc = """
<html><head><title>The Dormouse's story</title></head>

<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

 1.子节点

(1) tag的名字 
doc=BeautifulSoup(html_doc,'lxml')
soup=doc.head
>>>soup.title
<title>The Dormouse's story</title> 
>>>soup.head
<head><title>The Dormouse's story</title></head>

(2).contents 、.children 、.descendents
tag的 .contents 属性可以将tag的子节点以列表的方式输出:
通过tag的 .children 生成器,可以对tag的子节点进行循环:

for child in soup.children:  
  print(child)
    # <title>The Dormouse's story</title>

. descendants属性可以对所有tag的子孙节点进行递归循环
(3). .string、.strings、stripped_strings
如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点。如果tag包含了多个子节点,tag就无法确定 .string 方法应该调用哪个子节点的内容, .string 的输出结果是 None 。
如果tag中包含多个字符串 [2] ,可以使用 .strings 来循环获取:

    for string in doc.strings:
       print(repr(string))
    # u"The Dormouse's story"
    # u'\n\n'
    # u"The Dormouse's story"
    # u'\n\n'
    # u'Once upon a time there were three little sisters; and their names were\n'
    # u'Elsie'
    # u',\n'
    # u'Lacie'
    # u' and\n'
    # u'Tillie'
    # u';\nand they lived at the bottom of a well.'
    # u'\n\n'
    # u'...'
    # u'\n'

“`
输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值