BeautifulSoup的基本使用
一.BeautifulSoup的基本使用
使用BeautifulSoup可以分为几个步骤:
- 导入相关的库
from bs4 import BeautifulSoup
- 初始化BeautifulSoup对象
soup = BeautifulSoup(html,parser)
其中,html为获取得到的页面内容,如:
html
<html>
<head><title>BeautifulSoup</title></head>
<body>
BeautifulSoup
</body>
<html>
parser为解析器的名字,常用的一般为lxml,html.parser
通过上面的步骤,就可以完成一个基本的初始化,接下来就是利用soup来获取所需要的html中的信息
二.BeautifulSoup的基本对象种类
- Tag(类似与html与xml中的tag,包含有许多的方法)
- NavigableString(类似于pytho的str)
- BeautifulSoup(解析的文件的整体,可以想象成最大的tag)
- Comment(注释的类型)
三.基本对象种类的使用
1. Comment对象(个人感觉比较少使用)
Comment对象就是在解析获取得到的html中的注释信息类型,例:
from bs4 import BeautifulSoup
html = '''<html>
<head><title>BeautifulSoup</title></head>
<body>
<b><!--BeautifulSoup--></b>
</body>
<html>'''
soup = BeautifulSoup(html,'lxml')
print(type(soup.body.b.string))
输出为:
<class 'bs4.element.Comment'>
这个了解就好了,比较少用
2. BeautifulSoup对象(整体)
如上面的例子中。所获取得到的soup就是一个BeautifulSoup对象,它包含了整个文档所有的信息,我们可以通过这个对象来获取得到初步所需要的信息。
In [13]: print(type(soup))
<class 'bs4.BeautifulSoup'>
3.NavigableString对象
在获取得到的整个文档书中,当我们需要获取得到某个tag中的内容时,这个内容的类型就是NavigableString,Comment可以理解成特殊的NavigableString。例子如下:
from bs4 import BeautifulSoup
html = '''<html>
<head><title>BeautifulSoup</title></head>
<body>
<b>BeautifulSoup</b>
</body>
<html>'''
soup = BeautifulSoup(html,'lxml')
print(type(soup.body.b.string))
输出为:
<class 'bs4.element.NavigableString'>
4.tag对象(非常重要,在解析时主要使用的对象)
tag对象就是BeautifulSoup中的主要对象,tag定义有许多的方法,现在先了解tag是什么。例子如下:
from bs4 import BeautifulSoup
html = '''<html>
<head><title>BeautifulSoup</title></head>
<body>
<b>BeautifulSoup</b>
</body>
<html>'''
soup = BeautifulSoup(html,'lxml')
print(type(soup.body.b))
输出为:
<class 'bs4.element.Tag'>
每个标签,都是一个tag对象,我们可以通过tag对象中已经定义好的方法来获取想要得到的信息,现在可以看下tag大概包含有哪些方法,属性。
dir(soup.body.b)
由于结果太多,就不展示了,可以自己的shell中输入上面的命令来获取得到全部的方法