所使用的html为:
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>
</html>"""
.contents和.children
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
# <head><title>The Dormouse's story</title></head>
# [<title>The Dormouse's story</title>]
# <title>The Dormouse's story</title>
# [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
.descendants
.contents和 .children 属性仅包含 tag的直接子节点 。例如 :
head_tag.contents
# [<title>The Dormouse's story</title>]
而.descendants 属性是父标签下面所有级别的标签,例如,tr标签是table的子标签,而tr、th、td等都是table的后代标签,例如:
for child in head_tag.descendants:
print(child)
# <title>The Dormouse's story</title>
# The Dormouse's story
标签只有一个子节点,但是有 2个子孙节点。这个在之前讲过,BeautifulSoup将HTML解析为一棵树,以此来理解子节点与子孙节点就好理解了。
len(list(soup.children)) #这里是html的children子节点
# 1
len(list(soup.descendants)) #这里是html的descendants子孙节点 多个
# 25
.string
如果tag只有一个NavigableString 类型子节点 ,那么这个tag可以使用.string 得到子节点 :
title_tag.string
# u'The Dormouse's story'
如果一个tag仅有一个子节点 ,那么这个 tag也可以使用 .string 方法 ,输出结果与当前唯一子节点的 .string 结果相同。
如果 tag包含了多个子节点,tag就无法确定 .string方法应该调用哪个子节点的内 , .string 的输出结果是 None。
strings 和 stripped_strings
如果 tag中包含多个字符串 ,可以使用.strings 来循环获取 :
for string in soup.strings:
print(repr(string))
输出的字符串中 可能包含了很多空格或行 ,使用 .stripped_strings 可以去除多余空白内容 :
for string in soup.stripped_strings:
print(repr(string))
本文介绍了PythonBeautifulSoup库中处理HTML元素子节点的方法,包括.tag.contents用于获取子节点列表,.tag.children遍历直接子节点,.tag.descendants遍历所有后代节点。同时,讲解了.tag.string属性用于获取单一文本子节点,以及.strings和.stripped_strings用于处理多个字符串子节点并去除空白内容。
1365

被折叠的 条评论
为什么被折叠?



