Beautiful Soup解析库
1. Beautiful Soup 介绍与安装
Beautiful Soup是一个可以从HTML或XML文件中提取数据的Python库。
Beautiful Soup安装:
1.安装Beautiful Soup 4
pip install beautifulsoup4
2.安装 lxml
pip install lxml
2.BeautifulSoup对象介绍与创建
-
BeautifulSoup对象:代表要解析的整个文档树,支持遍历文档树和搜索文档树中描述的大部分的方法。
-
创建BeautifulSoup对象:
#1.导入模块 from bs4 import BeautifulSoup #2.创建BeautifulSoup对象 soup = BeautifulSoup('<html>data</html>', 'html.parser') # 参数为要解析的文档 print(soup)
3.BeautifulSoup对象的find方法
find方法:用于搜索文档树;
-
find(self,name=None,attrs={},recursive=Ture,text=None)
-
参数:
- name:标签名;
- attrs:属性字典;(返回的是含该属性内容的整个标签)
- recursive:是否递归循环查找;(递归循环查找才能查找到二级标题)
- text:根据文本查找内容;
-
返回值:
- 查找到的第一个元素对象;
- 使用find_all函数,会将整个所有查找到的对象做成一个列表返回;
-
查找演示:
#1.导入模块 from bs4 import BeautifulSoup #2.准备文档字符串 html='''<html> <head> <title>The kaakka</title> </head> <body> <p class="title"> <b>jssjjsj</b> </p> <p class="story">jsjsjsjncvncncn <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>; </p> <p class="story">...</p> </body> </html> ''' #3.创建BeautifulSoup对象 soup = BeautifulSoup(html, 'html.parser') # 参数为要解析的文档 #4.进行标签查找 title = soup.find(name="title")#查找title标签 a = soup.find('a') print(a) print(title) #5.按属性进行查找,查找id为link1的标签 ##方法1:通过命名参数进行指定(并不是所有时候都能作为参数传入函数) a1 = soup.find(id='link1') print(a1) print(type(a1))#<class 'bs4.element.Tag'>返回的是一个tag对象 ##方法2:使用attrs来指定属性字典 a2 = soup.find(attrs={'id' : 'link1'})#传入的参数必须为字典类型的参数 print(a2) #6.根据文本进行查找 text = soup.find(text='Elsie') print(text)
4.tag对象介绍
tag对象对应于原始文档中的XML或HTML标签,Tag对象有很多方法和属性,可用遍历文档树和搜索文档树以及获取标签内的内容。
-
**tag对象常见属性:**name:获取标签名称;attrs:获取标签所有属性的键和值;text:获取标签的文本;
-
代码演练:
#tag对象 print(type(a))#<class 'bs4.element.Tag'> print(a.name)#返回标签名 print(a.attrs)#获取所有属性,以字典形式返回 print(a.text)#获取标签内的文本内容
5 案例:从疫情首页提取出各国最新的疫情数据
#1.导入相关模块
import requests
from bs4 import BeautifulSoup
#2.发送请求,获取疫情首页内容
response = requests.get('https://ncov.dxy.cn/ncovh5/view/pneumonia')
home_page = response.content.decode()#获取文本字符串
# print(home_page)#查看是否能正常获取数据
#3.使用BeautifulSoup提取相应数据
soup = BeautifulSoup(home_page, 'html.parser')
script = soup.find(attrs={'id': "getListByCountryTypeService2true"})
text = script.string
print(text)