所使用的html为:
html_doc = """
<html>
<head><title>The Dormouse's storytitle>head>
<p class="title"><b>The Dormouse's storyb>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">Elsiea>,
<a href="http://example.com/lacie" class="sister" id="link2">Laciea> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilliea>; and they lived at the bottom of a well.p>
<p class="story">...p>
html>"""
tag的 .contents 属性可以将 tag的子节点以列表的形式输出。
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
head_tag = soup.head
print head_tag
head_tag.contents
title_tag = head_tag.contents[0]
print title_tag
print title_tag.contents
# The Dormouse's story
# [The Dormouse's story ]
# The Dormouse's story
# [u'The Dormouse's story']
BeautifulSoup对象本身一定会包含子节点 ,也就是说 标签也是 BeautifulSoup 对象的子节点 :
len(soup.contents)
# 1
soup.contents[0].name
# u'html'
字符串没有.contents 属性 ,因为字符串没有子节点 :
text = title_tag.contents[0]
print text.contents
# AttributeError: 'NavigableString' object has no attribute 'contents'
通过 tag的 .children ,可以对 tag的直接子节点(父标签的下一级)进行循环 :
for child in title_tag.children:
print(child)
# The Dormouse's story
.contents和 .children 属性仅包含 tag的直接子节点 。例如 :
head_tag.contents
# [<title>The Dormouse's storytitle>]
而.descendants 属性是父标签下面所有级别的标签,例如,tr标签是table的子标签,而tr、th、td等都是table的后代标签,例如:
for child in head_tag.descendants:
print(child)
# The Dormouse's story
# The Dormouse's story
标签只有一个子节点,但是有 2个子孙节点。这个在之前讲过,BeautifulSoup将HTML解析为一棵树,以此来理解子节点与子孙节点就好理解了。
len(list(soup.children)) #这里是html的children子节点
# 1
len(list(soup.descendants)) #这里是html的descendants子孙节点 多个
# 25
如果tag只有一个NavigableString 类型子节点 ,那么这个tag可以使用.string 得到子节点 :
title_tag.string
# u'The Dormouse's story'
如果一个tag仅有一个子节点 ,那么这个 tag也可以使用 .string 方法 ,输出结果与当前唯一子节点的 .string 结果相同。
如果 tag包含了多个子节点,tag就无法确定 .string方法应该调用哪个子节点的内 , .string 的输出结果是 None。
如果 tag中包含多个字符串 ,可以使用.strings 来循环获取 :
for string in soup.strings:
print(repr(string))
输出的字符串中 可能包含了很多空格或行 ,使用 .stripped_strings 可以去除多余空白内容 :
for string in soup.stripped_strings:
print(repr(string))