转自本人旧博客
title: BeautifulSoup
date: 2017-08-17 21:00:53
tags: python
categories: 爬虫
安装和使用
安装
pip install beautifulsoup4
使用
- 导入
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/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
-
创建beautifulsoup对象
soup = BeautifulSoup(html)
-
也可以用本地HTML文件来创建对象
soup = BeautifulSoup(open(‘index.html’))
-
格式化输出,打印出soup对象的内容
print soup.prettify()
四大对象种类
1. Tag
-
是HTML中的一个个标签:title、 a等等HTML标签加上里面包括的内容
-
验证下这些对象的类型
>>> print type(soup.a) <class 'bs4.element.Tag'>
属性
name
>>> print soup.name
[document]
>>> print soup.head.name
head
- suop对象本身比较特殊,它的 name 即为 [document],对于其他内部标签,输出的值便为标签本身的名称。
attrs
-
把 p 的所有属性打印出来
>>> print soup.p.attrs {'class': ['title'], 'name': 'dromouse'}
-
单独获取某个属性
>>> print soup.p['class'] ['title']
-
还可以用get方法
>>> 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 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
-
是一个特殊类型的 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'>
-
a 里的内容实际上是注释,利用 .string 来输出它的内容,已经把注释符号去掉了( 所以这可能会给我们带来不必要的麻烦 )
-
在使用前最好做一下判断
>>> if type(soup.a.string)==bs4.element.Comment: ... print soup.a.string
遍历文档树
待续先,累了==