【爬虫解析5】Beautiful Soup

 Beautiful Soup的用法

from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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)
	
#打印一下 soup 对象的内容,格式化输出	
print(soup.prettify())
	
	
#===================================	

#(1)Tag
#获取标签内容	
#soap+标签 查找的是在所有内容中的第一个符合要求的标签
print(soup.title)
	#<title>The Dormouse's story</title>
print(soup.head)
print(soup.a)
print(soup.p)
	#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
	

#验证对象类型	
print(type(soup.a))
	##<class 'bs4.element.Tag'>
	
#把 p 标签的所有属性打印输出了出来
print(soup.p.attrs)	
	# {'class': ['title'], 'name': 'dromouse'}

#Tag的name属性	
print(soup.name)	
print(soup.head.name)	
	#[document]
	#head
	
#单独获取某个属性
print(soup.p['class'])
	#['title']	
print(soup.p.get('class'))
	#['title']	
	
	
#更改或新增属性内容
soup.p['class']="newClass"
print(soup.p)
	#<p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>	
	
#删除属性	
del soup.p['class']
print(soup.p)
#<p name="dromouse"><b>The Dormouse's story</b></p>	
	

#=============================	
#(2)NavigableString
#获取标签内容
print(soup.p.string)	
	#The Dormouse's story

print(soup.a.string)	
	#Elsie
	
#标签内容类型
print(type(soup.p.string))
	##<class 'bs4.element.NavigableString'>
	

#=============================		
#(3)BeautifulSoup
#BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下	
print(type(soup.name))
	#<type 'unicode'>
print(soup.name)
	# [document]
print(soup.attrs) 
	#{} 空字典	
	
#=============================		
#(4)Comment
#Comment 对象是一个特殊类型的 NavigableString 对象,其实输出的内容仍然不包括注释符号	
print(soup.a)
	#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
print(soup.a.string)
	#Elsie 
print(type(soup.a.string))
	#<class 'bs4.element.Comment'>
	
	

 

遍历文档树

from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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)
	
print("==========================================")
#遍历文档树

#(1)直接子节点.contents  .children
#.contents 和 .children 属性仅包含tag的直接子节点
print(soup.head.contents)
	#[<title>The Dormouse's story</title>]
print(soup.head.contents[0]	)
	#<title>The Dormouse's story</title>
print(soup.head.contents[0].string	)
	#The Dormouse's story


print(soup.head.children)
	#<listiterator object at 0x7f71457f5710>
for child in  soup.head.children:
    print(child)
		#<title>The Dormouse's story</title>

print("=======================1")
	
for child in  soup.p.children:
    print(child)	
		#<b>The Dormouse's story</b>
	
print("=======================2")	
for child in  soup.body.children:
    print(child)


print("==========================================")
#(2)所有子孙节点.descendants 
for child in soup.descendants:
    print(child)

#(3)节点内容:.string 属性
#如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容。

print(soup.head.string)
#The Dormouse's story
print(soup.title.string)
#The Dormouse's story

#如果tag包含了多个子节点,tag就无法确定,string 方法应该调用哪个子节点的内容, .string 的输出结果是 None
print(soup.html.string)
# None


#(4)多个内容 .strings .stripped_strings 属性
#for string in soup.strings:
 #   print(repr(string))

#输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容
for string in soup.stripped_strings:
    print(repr(string))


#(5)父节点 .parent 属性	
p = soup.p
print(p.parent.name)
	#body	
print(soup.title.parent.name	)
	#head
	
	
#(6)全部父节点 .parents 	
content = soup.head.title.string
for parent in  content.parents:
    print(parent.name)
		#title
		#head
		#html
		#[document]
	
#(7)兄弟节点
#知识点:.next_sibling .previous_sibling 属性	
#兄弟节点可以理解为和本节点处在统一级的节点,.next_sibling 属性获取了该节点的下一个兄弟节点,.previous_sibling 则与之相反,如果节点不存在,则返回 None
#注意:实际文档中的tag的 .next_sibling 和 .previous_sibling 属性通常是字符串或空白,因为空白或者换行也可以被视作一个节点,所以得到的结果可能是空白或者换行	

print soup.p.next_sibling
#       实际该处为空白
print soup.p.prev_sibling
#None   没有前一个兄弟节点,返回 None
print soup.p.next_sibling.next_sibling
#<p class="story">Once upon a time there were three little sisters; and their names were
#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
#<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
#<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;
#and they lived at the bottom of a well.</p>


#(8)全部兄弟节点
#知识点:.next_siblings .previous_siblings 属性	
for sibling in soup.a.next_siblings:
    print(repr(sibling))	
	
#(9)前后节点
#知识点:.next_element .previous_element 属性	
#与 .next_sibling .previous_sibling 不同,它并不是针对于兄弟节点,而是在所有节点,不分层次

#<head><title>The Dormouse's story</title></head>
#那么它的下一个节点便是 title,它是不分层次关系的
print(soup.head.next_element)
#<title>The Dormouse's story</title>

	
#(10)所有前后节点
#知识点:.next_elements .previous_elements 属性	
for element in last_a_tag.next_elements:
    print(repr(element))	
	

。。

猜你喜欢

转载自uule.iteye.com/blog/2352872