Python爬虫之bs4库

来源:互联网 发布:php websocket 框架 编辑:程序博客网 时间:2024/05/29 14:21

python爬虫常用库之bs4


bs4全名BeautifulSoup,是编写python爬虫常用库之一,主要用来解析html标签。


1.安装

pip install beautifulsoup4

python -m pip install beautifulsoup4

2.基本使用方法

bs4中最基础的使用是BeautifulSoup类的使用,注意大小写哦。

用BeautifulSoup来解析html:

from bs4 import BeautifulSoupsoup1 = BeautifulSoup("<html> A Html Text</html>", "html.parser")soup2 = BeautifulSoup(open("d://demo.html"), "html.parser")
两个参数:第一个参数是要解析的html文本,第二个参数是使用那种解析器,对于HTML来讲就是html.parser,这个是bs4自带的解析器。 还可以安装lxml库来解析HTML或者XML,安装html5lib来解析html5lib。

#lxml解析html(需pip install lxml)BeautifulSoup(html,'lxml')#lxml解析XMLBeautifulSoup(xml,'xml')#html5lib解析(需安装: pip install html5lib)BeautifulSoup(html5,'html5lib')

2.1 BeautifulSoup基本元素

BeautifulSoup基本元素有:

基本元素说明Tag标签,基本信息组织单元,用<>和</>标明开头和结尾Name标签的名字,<p>...</p>的名字就是’p',用法<>.nameAttributes标签属性,字典形式,用法:<>.attrs['href']NavigableString标签内非属性字符串,<p>这是非属性字符串</p>,用法:<>.stringComment标签内的注释部分<p>显示的内容<!-- comment就是这里啦--></p>2.1.1 Tag标签

任何存在于html语法中的标签都可以用soup.<tag>访问获得。

当HTML文档中存在多个相同的tag时,soup.<tag>返回第一个

>>> soup2 = BeautifulSoup("<p class=\"title\"><b>The Contents of b in first p</b></p><p class=\"course\">The second p</p>","html.parser")>>> soup2.p<p class="title"><b>The Contents of b in first p</b></p>

2.1.2 Tag的name

每个Tag都有自己的名字,通过<tag>.name获取,字符串类型

>>> soup2.p.name'p'
2.1.3 Tag的attrs(属性)

一个Tag可以有0个或多个属性,字典类型。

>>> soup2.p.attrs{'class': ['title']}>>> soup2.p.attrs['class']['title']

2.1.4 Tag的NavigableString

NavigableString可以跨越多个层次的标签。

>>> soup2.p<p class="title"><b>The Contents of b in first p</b></p>>>> soup2.p.string'The Contents of b in first p'>>> 

2.1.5 Tag 的Comment

Comment是一种特殊类型

>>> soup3 = BeautifulSoup("<p>This is a NavigableString</p><b><!-- This is a Comment --></b>","html.parser")>>> soup3.p<p>This is a NavigableString</p>>>> soup3.b<b><!-- This is a Comment --></b>>>> soup3.p.string'This is a NavigableString'>>> type(soup3.p.string)<class 'bs4.element.NavigableString'>>>> soup3.b<b><!-- This is a Comment --></b>>>> soup3.b.string' This is a Comment '>>> type(soup3.b.string)<class 'bs4.element.Comment'>>>> 


<p class="title">....</p>
p ->tag.name  'p'

class="title" -> tag.attrs (字典列表)

... -> NavigableString OR Comment

2.2 使用bs4遍历html内容

HTML是个树状结构,<>...</>构成了从属关系。对HTML的遍历,有下行遍历,上行遍历和平行遍历三种遍历途径或方法。

2.2.1 下行遍历

属性说明.contents子节点的列表,将<tag>所有的儿子节点存入列表.children子节点的迭代类型,与.contents类似,主要用于循环遍历子节点.descendants子孙节点的迭代类型,包含所有子孙节点,用于循环遍历。

BeautifulSoup类型是标签树的根节点。

soup.headsoup.head.contentssoup.body.contentslen(soup.body.contents)soup.body.contents[0]
遍历子节点:
for child in soup.body.children:    print(child)
遍历所有子孙节点:

for child in soup.body.descendants:    print(child)

2.2.2 上行遍历

属性说明.parent节点的父节点.parents节点的先辈节点标签的迭代类型,用于循环遍历先辈节点。

>>> soup<html><head><title>This is a python demo page</title></head><body><p class="title"><b>The demo python introduces several python courses.</b></p><p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p></body></html>>>> soup.title.parent<head><title>This is a python demo page</title></head>>>> soup.html.parent<html><head><title>This is a python demo page</title></head><body><p class="title"><b>The demo python introduces several python courses.</b></p><p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p></body></html>>>> soup.parent>>> 
注意:<html>..</html>标签的父节点是其自身

而soup本身的父节点是空。

进行先辈节点遍历时,包括soup自身,实际使用时需要判断。

for parent in soup.a.parents:if parent is None:print(parent)else:print(parent.name)

2.2.3 平行遍历

属性说明.next_sibling返回按照HTML文本顺序的下一个平行节点标签.previous_sibling返回按照HTML文本顺序的上一个平行节点标签.next_siblings迭代类型,返回按照HTML文本顺序的后续所有平行节点标签.previous_siblings迭代类型,返回按照HTML文本顺序的前续所有平行节点标签平行遍历发生在同一个父节点下的各节点之间。

soup.a.next_siblingsoup.a.next_sibling.nextsiblingsoup.a.previous_siblingsoup.a.parent

遍历后续节点:

for sibling in soup.a.next_siblings:print(sibling)

遍历前续节点:

for sibling in previous_siblings:print(sibling)

3. 基于bs4库的HTML格式输出

3.1 prettify()方法

.prettify()为HTML文本<>及其内容增加‘\n'

.prettify()可用于标签,方法<tag>.prettify()

print(soup.a.prettify())

3.2 bs4k库的编码

bs4库将任何HTML输入都变成utf-8编码,python3.x 默认支持编码是utf-8。完美匹配!


4.使用bs4进行HTML内容查找

使用bs4进行HTML内容解析查找,基本方法是使用<>.find_all()来进行

4.1 .find_all()的基本使用方法

基本格式:

<tag>.find_all(name, attrs, recursive, string, **kwargs)

其返回值为一个列表,存储查找的结果

参数:

name -> 对标签名称的检索字符串,可以是个字符串列表,表达“或”关系

soup.find_all('a')soup.find_all(['a','b'])soup.find_all(True)


attrs -> 对标签属性值的检索字符串,可标注属性检索

soup.find_all('a', 'title')soup.find_all(id='link1')soup.find_all(attrs = {"class":"course"})

recursive -> 是否对子孙全部检索,默认True

string -> <>...</>中的....的检索字符串

soup.find_all(string = 'This is a sample')


因为find_all太常用了,所以有简略用法:

<tag>(...) <--><tag>.find_all(...)

soup(...) <-->soup.find_all(...)

程序员果然都是懒人..........大笑

4.2 扩展方法

方法说明<>.find()搜索且只返回一个结果,同.find_all()参数<>.find_parents()在先辈节点中搜索,返回列表类型,同.find_all()参数<>.find_parent()在先辈节点中返回一个结果,同.find()参数<>.find_next_siblings()在后续平行节点中搜索,返回列表类型,同find_all()参数<>.find_next_sibling()在后续平行节点中搜索,返回一个结果,同find()参数<>.find_previous_siblings()在前续平行节点中搜索,返回列表类型,同find_all()参数<>.find_previous_sibling()在前续平行节点中搜索,返回一个结果,同find()参数

0 0
原创粉丝点击