05--BS4回顾

发布时间 2023-12-25 21:08:49作者: Edmond辉仔

Beautiful Soup

一 简单使用

简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:

Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能
它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序

1.安装

pip install beautifulsoup4

1.1 解析器

Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器

默认的解析器为html.parser,lxml 解析器更加强大,速度更快,推荐安装

pip install lxml

1.2 解析器对比

官网文档

2.如何使用

将一段文档传入BeautifulSoup 的构造方法,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄

然后Beautiful Soup选择最合适的解析器来解析这段文档,可指定解析器,来解析文档

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("index.html"), 'lxml')

soup = BeautifulSoup("<html>data</html>", 'lxml')

3.对象的种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构

每个节点都是Python对象,所有对象可以归纳为种

Tag , NavigableString , BeautifulSoup , Comment .

3.1 Tag标签

通俗点讲就是 HTML 中的一个个标签,Tag 对象与XML或HTML原生文档中的tag相同:

soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')

tag = soup.b

type(tag) # <class 'bs4.element.Tag'>

# tag中多次调用这个方法
soup.body.b  # 获取<body>标签中的第一个<b>标签

3.2 name和attributes属性

Tag的方法和属性: name和attributes

### 1 获取标签的名字
tag.name  # 'b'


### 2 获取标签的属性 
# 方式一:.attrs 所有属性变成字典
tag.attrs  # {'class': 'boldest'}

tag.attrs['class']  # 'boldest'


# 方式二:直接 ['属性']
tag['class']   # 'boldest'


### 3 标签属性的修改
属性可被添加,删除或修改. 操作方法与字典一样(了解)
tag['class'] = 'verybold'
tag['id'] = 1

tag  # <blockquote class="verybold" id="1">Extremely bold</blockquote>

3.3 NavigableString(字符串)

获取标签内部的文字怎么办呢?用 .string 即可.

字符串常被包含在tag内.Beautiful Soup用 NavigableString 类来包装tag中的字符串

### 详见:节点内容
tag.string
# 'Extremely bold'

type(tag.string)
# <class 'bs4.element.NavigableString'>

3.4 BeautifulSoup

BeautifulSoup 对象表示的是一个文档的全部内容

可把它当作 Tag 对象,是一个特殊的 Tag

可分别获取它的类型,名称,以及属性

print(type(soup.name))
# <class 'str'>

print(soup.name)
# [document]

print(soup.attrs)
# {} 空字典

3.5 Comment

如果字符串内容为注释 则为Comment

html_doc='<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>'

soup = BeautifulSoup(html_doc, 'html.parser')

print(soup.a.string)   # Elsie
print(type(soup.a.string))  #  <class 'bs4.element.Comment'>

# 注:
a标签里的内容实际上是注释
但若利用 .string 来输出它的内容
发现它已经把注释符号去掉了  # !!!

二 遍历文档树

拿”爱丽丝梦游仙境”的文档来做例子:

html_doc = """
<html><head><title>The Dormouse's story</title></head>
    <body>
<p class="title"><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>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')

1.子、子孙节点

一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点

Beautiful Soup提供了许多操作和遍历子节点的属性

注意: Beautiful Soup中字符串节点不支持这些属性,因为字符串没有子节点。

1.1 .contents 和 .children

  • tag的 .contents 属性,将tag的子节点以列表的方式输出:
head_tag = soup.head

head_tag
# <head><title>The Dormouse's story</title></head>

head_tag.contents
# [<title>The Dormouse's story</title>]

title_tag = head_tag.contents[0]
title_tag
# <title>The Dormouse's story</title>
 
title_tag.contents
# [u'The Dormouse's story']

# 字符串没有 .contents`属性,因为字符串没有子节点:
text = title_tag.contents[0]

text.contents
# AttributeError: 'NavigableString' object has no attribute 'contents'
  • tag的 .children 生成器,可对tag的子节点进行循环:
print(title_tag.children)       # <list_iterator object at 0x101b78860>

print(type(title_tag.children)) # <class 'list_iterator'>

for child in title_tag.children:
    print(child)
    # The Dormouse's story

1.2 .descendants

  • tag的 .descendants 属性,可对所有tag的子孙节点进行递归循环
for child in head_tag.descendants:
    print(child)
    # <title>The Dormouse's story</title>
    # The Dormouse's story

2.节点内容

2.1 .string

若标签里面只有文本,或,标签里面只有一个标签

.string 返回文本内容

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

# <title><b>The Dormouse's story</b></title>

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


# 注:
若tag包含了多个子节点,tag就无法确定 string方法 应该调用哪个子节点的内容
.string 的输出结果是 None

print (soup.html.string)
# None

2.2 .text

如果tag包含了多个子节点,text则会返回内部所有文本内容

print (soup.html.text)

注意:

strings和text都可以返回所有文本内容

区别:text返回内容为字符串类型 strings为生成器generator

3.多个内容

3.1 .strings

获取多个内容,不过需要遍历获取,比如下面的例子:

for string in soup.strings:
    print(repr(string))
    
    
'''
  '\n'
"The Dormouse's story"
'\n'
'\n'
"The Dormouse's story"
'\n'
'Once upon a time there were three little sisters; and their names were\n'
'Elsie'
',\n'
'Lacie'
' and\n'
'Tillie'
';\nand they lived at the bottom of a well.'
'\n'
'...'
'\n'  
    
'''    

3.2 .stripped_strings

使用 .stripped_strings 可以去除多余空白字符

for string in soup.stripped_strings:
    print(repr(string))


'''
"The Dormouse's story"
"The Dormouse's story"
'Once upon a time there were three little sisters; and their names were'
'Elsie'
','
'Lacie'
'and'
'Tillie'
';\nand they lived at the bottom of a well.'
'...'
'''

4.父节点

4.1 .parent

通过元素的.parent 属性来获取某个元素的父节点.

title_tag = soup.title

title_tag
# <title>The Dormouse's story</title>

title_tag.parent
# <head><title>The Dormouse's story</title></head>

4.2 .parents

通过元素的 .parents 属性,可以递归得到元素的所有父辈节点

link = soup.a

link
# <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

for parent in link.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)
# p
# body
# html
# [document]
# None

三 搜索文档树

这块儿有点乱,直接看 爬虫03--bs4解析库

1.find_all()

# find_all()方法
搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件:


def find_all(name, attrs, recursive, string , **kwargs)


# 参数:name, keyword, text  都允许五种过滤器:字符串、正则表达式、列表、方法、True

1.1 name 参数

name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉

简单的用法如下:

soup.find_all("title")
# [<title>The Dormouse's story</title>]

搜索 name 参数的值可以使任一类型的 过滤器

  • 1 传字符串

在搜索方法中传入一个字符串参数,bs4 会查找与字符串完整匹配的内容

soup.find_all('b')
# [<b>The Dormouse's story</b>]
  • 2 传正则表达式

如果传入正则表达式作为参数,bs4 会通过正则表达式的 match() 来匹配内容

import re

for tag in soup.find_all(re.compile("^b")):
    print(tag.name)
# body
# b
  • 3 传列表

如果传入列表参数,bs4 会将与列表中任一元素匹配的内容返回 或

soup.find_all(["a", "b"])
# [<b>The Dormouse's story</b>,
#  <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

1.2 keyword 参数

    1. 如果一个指定关键字的参数,不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索
# 如果包含一个名字为 id 的参数,bs4会搜索每个tag的id属性
soup.find_all(id='link2')
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

import re
# 超链接包含elsie标签
print(soup.find_all(href=re.compile("elsie")))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
    1. 使用多个指定名字的参数,可以同时过滤tag的多个属性 并
soup.find_all(href=re.compile("elsie"), id='link1')
# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
    1. class 过滤,class 是 python 的关键词,需要额外加 下划线
print(soup.find_all("a", class_="sister"))

'''
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
'''
    1. attrs 参数定义一个字典参数,来搜索包含特殊属性的tag:
data_soup.find_all(attrs={"data-foo": "value"})
# [<div data-foo="value">foo!</div>]

注意:如何查看条件id和class同时存在时的写法

print(soup.find_all('b', class_="story", id="x"))

print(soup.find_all('b', attrs={"class":"story", "id":"x"}))

1.3 text 参数

通过 text 参数可以搜搜文档中的字符串内容

import re

print(soup.find_all(text="Elsie"))
# ['Elsie']

print(soup.find_all(text=["Tillie", "Elsie", "Lacie"]))
# ['Elsie', 'Lacie', 'Tillie']

# 只要包含Dormouse就可以
print(soup.find_all(text=re.compile("Dormouse")))
# ["The Dormouse's story", "The Dormouse's story"]

1.4 limit 参数

可使用 limit 参数限制返回结果的数量

print(soup.find_all("a",limit=2))
print(soup.find_all("a")[0:2])

'''
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, 
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
'''

2.find()

find() :找到一个,直接返回结果

find_all() :找到所有,返回是多元素的列表

def find(name , attrs , recursive , string , **kwargs )


# 以下等同
soup.find_all('title', limit=1)
# [<title>The Dormouse's story</title>]

soup.find('title')
# <title>The Dormouse's story</title>

3.find_parents()、find_parent()

a_string = soup.find(text="Lacie")
print(a_string)  # Lacie

print(a_string.find_parent())
# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>
print(a_string.find_parents())
print(a_string.find_parent("p"))
'''
<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>
'''

四 BS的css选择器

soup.select()来筛选元素,返回类型是 list

1.标签名查找

print(soup.select("title"))  #[<title>The Dormouse's story</title>]
print(soup.select("b"))      #[<b>The Dormouse's story</b>]

2.类名查找

print(soup.select(".sister")) 

'''
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, 
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, 
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

'''

3.id名查找

print(soup.select("#link1"))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

4.组合查找

print(soup.select("p #link2"))

#[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

直接子标签查找

print(soup.select("p > #link2"))
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

查找既有class也有id选择器的标签

a_string = soup.select(".story#test")

查找有多个class选择器的标签

a_string = soup.select(".story.test")

查找有多个class选择器和一个id选择器的标签

a_string = soup.select(".story.test#book")

5.属性查找

查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。

print(soup.select("a[href='http://example.com/tillie']"))
# [<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容:

for title in soup.select('a'):
    print (title.get_text())

'''
Elsie
Lacie
Tillie
'''