【Python】Beautiful Soup

发布时间 2023-05-06 09:28:26作者: Hello、Lin
  • Beautiful Soup 对象 我全部使用soup表示;
  • Beautiful Soup 简介:
    简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。

1、创建Beautiful Soup 对象

1.1 soup.prettify()

from bs4 import BeautifulSoup
html_content = """  
<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>  
"""
#使用html5lib 解释器解释html_conten的内容
soup = BeautifulSoup(html_content,"html5lib")

# 格式化输出html
print(soup.prettify())

该方法是将html进行格式化,输出的内容就是格式化后的html代码。
image.png

1.2 soup.标签名

# 输出第一个 title 标签
print(soup.title)
#<title>The Dormouse's story</title>
# 输出第一个 p 标签
print(soup.p)
# <p class="title" name="dromouse"><b>The Dormouse's story</b></p>

1.3 soup.标签名.name

# 输出第一个 title 标签的标签名称
print(soup.title.name)
# title

# 输出第一个 p 标签的标签名称
print(soup.p.name)
# p

1.4 soup.标签名.string

# 输出第一个 title 标签的包含内容
print(soup.title.string)
# The Dormouse's story

# 输出第一个 p 标签的包含内容
print(soup.p.string)
# The Dormouse's story

1.5 soup.标签名.parent.name

# 输出第一个 title 标签的父标签的标签名称
print(soup.title.parent.name)
# head

# 输出第一个 title 标签的父标签的标签名称
print(soup.p.parent.name)
# body

1.6 soup.标签名['属性名']

# 输出第一个 p 标签的 class 属性内容
print(soup.p['class'])
# ['title']
# 输出第一个 a 标签的  href 属性内容
print(soup.a['href'])
# http://example.com/elsie

1.7 修改、删除、添加soup的属性

#操作方法与字典一样 
# 修改第一个 a 标签的href属性为 http://www.baidu.com/
soup.a['href'] = 'http://www.baidu.com/'

# 给第一个 a 标签添加 name 属性
soup.a['name'] = u'百度'

# 删除第一个 a 标签的 class 属性为
del soup.a['class']

print(soup.a)
#<a href="http://www.baidu.com/" id="link1" name="百度"><!-- Elsie --></a>

1.8 soup.标签名.contents

##输出第一个 p 标签的所有子节点
print(soup.p.contents)
#[<b>The Dormouse's story</b>]

1.9 soup.find()

# 输出第一个 id 属性等于  link3 的  a 标签
print(soup.find(id="link3"))
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
# 输出第一个  a 标签
print(soup.find('a'))
# <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
#查找ID位link2的a标签的文本
find_a = soup.find('a',id='link2')
print(find_a)
# The Dormouse's story

1.10 soup.find_all()

  • 得到是一个序列,我们可以是用遍历的方式对其进行输出,可以得到它的相关属性以及文本的值;
# 输出所有的 a 标签,以列表形式显示
# print(soup.find_all('a'))
#[<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>]

# 查找所有的a标签
find_all_a = soup.find_all('a')
print("查找所有的a标签")
for a_tag in find_all_a:
   print(a_tag.getText())
   print(a_tag.get('href'))


print soup.find_all("a", class_="sister")  
 
# 通过属性进行查找  
print soup.find_all("a", attrs={"class": "sister"})  
 
# 通过文本进行查找  
print soup.find_all(text="Elsie")  
print soup.find_all(text=["Tillie", "Elsie", "Lacie"])  
 
# 限制结果个数  
print soup.find_all("a", limit=2)

1.11 get_text()

#获取所有文字内容
print(soup.get_text())
'''
The Dormouse's story  
  
The Dormouse's story  
Once upon a time there were three little sisters; and their names were  
,  
Lacie and  
Tillie;  
and they lived at the bottom of a well.  
...  
'''
#获取第一个p标签的内容
print(soup.p.get_text())
# The Dormouse's story

1.12 soup.标签名.attrs

# 输出第一个  a 标签的所有属性信息
print(soup.a.attrs)
# {'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}

1.13 正则匹配

# 正则匹配,名字中带有b的标签
for tag in soup.find_all(re.compile(r"b")):
    print(tag.name)
"""
body
b
"""

2、四大内置对象

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

2.1 Tag

  • Tag 是什么?通俗点讲就是 HTML 中的一个个标签;
  • 两个重要的属性,是 nameattrs

name

print(soup.name)
# soup 对象本身比较特殊,它的 name 即为 [document],对于其他内部标签,输出的值便为标签本身的名称。
print(soup.a.name)
# a

attrs

print(soup.p.attrs)
#{'class': ['title'], 'name': 'dromouse'}
#在这里,我们把 p 标签的所有属性打印输出了出来,得到的类型是一个字典。

#如果要获取到某个属性的值,我们可以这样:
print(soup.p['name'])
# dromouse
print(soup.p.get('name'))
# dromouse

删除、修改属性

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> 

contents[n] 获取第n个节点的内容

head = soup.find('head')  
#head = soup.head  
#head = soup.contents[0].contents[0]  
print head  
  
html = soup.contents[0]       # <html> ... </html>  
head = html.contents[0]       # <head> ... </head>  
body = html.contents[1]       # <body> ... </body>

2.2 NavigableString

string

  • 获取到标签里面的内容
# 获取到第一个p 标签的内容
print(soup.p.string)

2.3 BeautifulSoup

BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下

print type(soup.name)  
#<type 'unicode'>  
print soup.name   
# [document]  
print (soup.attrs )  
#{} 空字典

2.4 Comment

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'>

本文参考:[python BeautifulSoup库用法总结
](https://www.cnblogs.com/scios/p/8652760.html)