BeautifulSoup_第一节

 源自http://cuiqingcai.com/1319.html

 

import bs4
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 = BeautifulSoup(open('index.html))

#print(soup.prettify())
'''
#Tag  通俗点讲就是 HTML 中的一个个标签
#我们可以利用 soup加标签名轻松地获取这些标签的内容,是不是感觉比正则表达式方便多了?
# 不过有一点是,它查找的是在所有内容中的第一个符合要求的标签
#print(soup.title)

#Tag的name属性
print(soup.name)
print(soup.head.name)
#Tag的attrs属性
#获取p标签的所有属性,返回字典
print(soup.p.attrs)
#获取单个属性
print(soup.p['class'])
print(soup.p.get('class'))

'''
'''
#NavigableString         可以遍历的字符串
#获取标签内部的文字
print(soup.p.string)

#BeautifulSoup 对象表示的是一个文档的全部内容.
# 大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag
# 我们可以分别获取它的类型,名称,以及属性来感受一下
print(type(soup.name))
print(soup.name)
print(soup.attrs)
'''
'''
#Comment
#Comment 对象是一个特殊类型的 NavigableString 对象,
# 其实输出的内容仍然不包括注释符号,但是如果不好好处理它,可能会对我们的文本处理造成意想不到的麻烦。
print(soup.a)
print(soup.a.string)
print(type(soup.a.string))

#a 标签里的内容实际上是注释,但是如果我们利用 .string 来输出它的内容,我们发现它已经把注释符号去掉了
#另外我们打印输出下它的类型,发现它是一个 Comment 类型,所以,我们在使用前最好做一下判断
if type(soup.a.string)==bs4.element.Comment:
    print(soup.a.string)
'''
#6. 遍历文档树
#(1)直接子节点------  .contents   .children属性
#tag 的 .content 属性可以将tag的子节点以-列表-的方式输出
print(soup.head.contents)

#.children它返回的不是一个 list,不过我们可以通过遍历获取所有子节点。
#我们打印输出 .children 看一下,可以发现它是一个 list 生成器对象
print(soup.head.children)
for child in soup.body.children:
    print(child)

#(2)所有子孙节点  .descendants 属性
#运行结果如下,可以发现,所有的节点都被打印出来了,先生最外层的 HTML标签,其次从 head 标签一个个剥离,以此类推。
#一层一层剥开它的标签
for child in soup.descendants:
    print(child)
#(3)节点内容   .string 属性
#如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点。
# 如果一个tag仅有一个子节点,那么这个tag也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同。
#也就是说 如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容
print(soup.head.string)
print(soup.title.string)
#如果tag包含了多个子节点,tag就无法确定,string 方法应该调用哪个子节点的内容, .string 的输出结果是 None
print(soup.html.string)

#(4)多个内容 .strigs  .stripped_strings 属性
#.strings  获取多个内容,不过需要遍历获取
for strings in soup.strings:
    print(repr(strings))
# .stripped_strings  输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容
for strings in soup.stripped_strings:
    print(repr(strings))
#(5)父节点  .parent 属性

p = soup.p
print(p.parent.name)

content = soup.head.title.string
print(content.parent.name)
#(6)全部父节点   .parents
content = soup.head.title.string
for parent in content.parents:
    print(type(parent))
    print(parent.name)

  

posted @ 2017-11-30 21:54  慵懒的仙人掌  阅读(129)  评论(0编辑  收藏  举报