BS4解析库

Beautiful Soup4解析库

一、简介

1.简介

BeautifulSoup 是一个从HTML或XML文件中提取数据的Python解析库,使用方式简单方便,借助网页的结构和属性等特性来解析网页

2.安装

pip install beautifulsoup4

3.官方中文文档

https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

二、解析器

1.解析器

解析器使用方法优势劣势
Python标准库BeautifulSoup(markup, “html.parser”)Python的内置标准库执行速度适中、文档容错能力强Python 2.7.3 or 3.2.2之前 的版本中文档容错能力差
lxml HTML解析器BeautifulSoup(markup, “lxml”)速度快、文档容错能力强需要安装C语言库
lxml XML解析器BeautifulSoup(markup, [“lxml”, “xml”])速度快、唯一支持XML的解析器需要安装C语言库
html5libBeautifulSoup(markup, “html5lib”)最好的容错性、以浏览器的方式解析文档生成HTML5格式的文档速度慢、不依赖外部扩展

lxml解析器有解析HTML和XML的功能,速度快,容错力强,推荐使用

2.初始化

from bs4 import BeautifulSoup

html_doc = ""
soup = BeautifulSoup(html_doc, "lxml")	# html_doc为HTML字符串,"lxml"为解析器的类型
print(type(soup))		# <class 'bs4.BeautifulSoup'>

3.基本用法

from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.prettify())	# 把要解析的字符串以标准的缩进格式输出,并且自动更正

************************************************************************
<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 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>
  <p class="story">
   ...
  </p>
 </body>
</html>

三、节点选择器

1.选择元素

直接用节点名称选择节点元素,当有多个节点时只会匹配第一个节点,后面的会被忽略

from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.title)
print(type(soup.title))		# 为Tag类型
print(soup.a)	# 多个节点只匹配第一个
**********************************************************************
<title>The Dormouse's story</title>
<class 'bs4.element.Tag'>
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

2.提取信息

  • 获取名称:name
  • 获取所有属性:attrs 返回结果是字典形式
  • 获取某个属性:attrs[“要获取的属性”]、节点元素[“要获取的属性”]
  • 获取内容:string 返回结果是NavigableString类型
  • 获取内容:get_text() 返回结果是字符串类型
from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.a.name)
print(soup.a.attrs)
print(soup.a.attrs["id"])
print(soup.a["id"])
print(soup.title.string)
print(type(soup.title.string))
print(soup.title.get_text())
print(type(soup.title.get_text()))
**********************************************************************
a
{'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}
link1
link1
The Dormouse's story
<class 'bs4.element.NavigableString'>
The Dormouse's story
<class 'str'>

3.嵌套选择

Tag类型的基础上在此选择得到的依旧是Tag类型,因此能够嵌套选择

from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.head.title)
print(type(soup.head.title))
print(soup.head.title.string)
**********************************************************************
<title>The Dormouse's story</title>
<class 'bs4.element.Tag'>
The Dormouse's story

4.关联选择

  • 直接子节点:contents 返回结果是列表形式

  • 直接子节点:children 返回结果是生成器类型

  • 所有子孙节点:descendants 返回结果是生成器类型(它会递归查询所有的子节点,得到所有的子孙节点)

  • 父节点:parent

  • 祖先节点:parents 返回结果是生成器类型

  • 下一个兄弟节点:next_sibling

  • 上一个兄弟节点:previous_sibling

from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print("="*30 + "直接子节点")
print(soup.head.contents, type(soup.head.contents))
print(soup.head.children, type(soup.head.children))
print("="*30 + "所有子孙节点")
print(soup.head.descendants, type(soup.head.descendants))
for child in soup.head.descendants:
    print(child)
print("="*30 + "父节点")
print(soup.head.parent, type(soup.head.parent))
print("="*30 + "祖先节点")
print(soup.head.parents, type(soup.head.parents))
print("="*30 + "兄弟节点")
print(soup.a.next_sibling, type(soup.a.next_sibling))
print(soup.a.previous_sibling, type(soup.a.previous_sibling))
**********************************************************************
==============================直接子节点
[<title>The Dormouse's story</title>] <class 'list'>
<list_iterator object at 0x000002DFCB0F69E8> <class 'list_iterator'>
==============================所有子孙节点
<generator object Tag.descendants at 0x000002DFCB0C69A8> <class 'generator'>
<title>The Dormouse's story</title>
The Dormouse's story
==============================父节点
<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 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>
<p class="story">...</p>
</body></html> <class 'bs4.element.Tag'>
==============================祖先节点
<generator object PageElement.parents at 0x000002DFCB0C69A8> <class 'generator'>
==============================兄弟节点
,
 <class 'bs4.element.NavigableString'>
Once upon a time there were three little sisters; and their names were
 <class 'bs4.element.NavigableString'>

四、方法选择器

1.find_all()

查询所有符合条件的元素,返回结果为列表形式

find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)
  • name:匹配节点名
  • attrs:匹配属性的键值对
  • text:匹配节点的文本
from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.find_all(name="a"))
print(soup.find_all(name="a")[0])
print(soup.find_all(attrs={"id": "link1"}))
print(soup.find_all(text="Elsie"))
**********************************************************************
[<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 class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
['Elsie']

2.find()

返回第一个匹配的元素

from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.find(name="a"))
**********************************************************************
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

3.其他

五、CSS选择器

1.select()

调用select方法,传入相应的CSS选择器,返回结果为列表形式,支持嵌套选择

from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.select('title'))
print(soup.select('#link1'))
print(soup.select('.sister'))
**********************************************************************
[<title>The Dormouse's story</title>]
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</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>]

2.获取属性

直接传入[“属性名”],或者通过attrs[“属性名”]

from bs4 import BeautifulSoup

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>
"""
soup = BeautifulSoup(html_doc, "lxml")
print(soup.select('a')[0]["id"])
print(soup.select('a')[0]["class"])		# class属性返回结果为列表
print(soup.select('a')[0].attrs["class"])
print(soup.select('a')[0].attrs["href"])
**********************************************************************
link1
['sister']
['sister']
http://example.com/elsie
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值