python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python BeautifulSoup4

Python数据解析之BeautifulSoup4的用法详解

作者:素年凉音

Beautiful Soup 是一个可以从 HTML 或 XML 文件中提取数据的 Python 库,这篇文章主要来和大家介绍一下BeautifulSoup4的用法,需要的可以参考一下

BeautifulSoup 是什么

Beautiful Soup 是一个可以从 HTML 或 XML 文件中提取数据的 Python 库。,最主要的功能是从网页抓取数据。能够通过自己喜欢的转换器实现惯用的文档导航,查找,修改文档的方式。

注:BeautifulSoup3目前已经停止开发,官网推荐在现在的项目中使用BeautifulSoup4

bs4的安装

可以在 Pycharm 中,输入以下语句:然后可根据提示进行安装。

from bs4 import BeautifulSoup

注意:bs4 是依赖 lxml 库的,只有先安装 lxml 库才可以安装bs4库*

文档解析器优缺点

推荐使用 lxml 作为解析器,因为效率更高。

bs4 的使用

代码实例:

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 对象
soup = BeautifulSoup(html_doc, 'lxml')
print(soup, type(soup))  # <class 'bs4.BeautifulSoup'>
# 格式化文档输出
print(soup.prettify())
# 获取 title 标签的名称 title
print(soup.title.name)  # title
# 获取 title 标签内容
print(soup.title)  # <title>The Dormouse's story</title>
# title 标签里面的文本内容
print(soup.title.string)
# 获取 p 段落
print(soup.p)

bs4的对象种类

代码实例

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>
"""
"""
tag:标签
NavigableString:可导航的字符串,标签中的文本对象
beautifulSoup:bs对象,整个 html 文本对象
Comment:注释,如果 html 标签中有注释,则可过滤注释符号并保留注释文本
"""
# html_doc 表示要解析的文档,而 html.parser 表示解析文档时所用的解析器
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup)
""" tag:标签"""
print(type(soup.title))
print(type(soup.p))
print(type(soup.a))
""" NavigableString,可导航的字符串"""
from bs4.element import NavigableString
print(type(soup.title.string))   # 标签下的文本数据
"""beautifulSoup,bs对象"""
print(type(soup))
""" Comment:注释"""
html = "<b><!--好好学习,天天向上--></b>"
soup2 = BeautifulSoup(html, 'html.parser')
print(soup2.b.string, type(soup2.b.string))

遍历文档树

遍历子节点

遍历父节点

遍历兄弟节点

代码实例

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>
</body>
</html>
"""
soup = BeautifulSoup(html_doc, 'lxml')
r1 = soup.title.string  # 获取单个标签里面的内容  The Dormouse's story
# 获取html中所有的标签中的内容
r2 = soup.html.strings  # 返回是一个生成 generator对象,用过来获取多个标签内容
for i in r2:
    print(i)
r3 = soup.html.stripped_strings  # 获取html中所有的标签中的内容,并去掉多余的空格
for i in r3:
    print("---", i)

搜索文档树

代码实例

from bs4 import BeautifulSoup
html = """
<table class="tablelist" cellpadding="0" cellspacing="0">
    <tbody>
        <tr class="h">
            <td class="l" width="374">职位名称</td>
            <td>职位类别</td>
            <td>人数</td>
            <td>地点</td>
            <td>发布时间</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=33824&keywords=python&tid=87&lid=2218">22989-金融云区块链高级研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=29938&keywords=python&tid=87&lid=2218">22989-金融云高级后台开发</a></td>
            <td>技术类</td>
            <td>2</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31236&keywords=python&tid=87&lid=2218">SNG16-腾讯音乐运营开发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>2</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31235&keywords=python&tid=87&lid=2218">SNG16-腾讯音乐业务运维工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=34531&keywords=python&tid=87&lid=2218">TEG03-高级研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=34532&keywords=python&tid=87&lid=2218">TEG03-高级图像算法研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31648&keywords=python&tid=87&lid=2218">TEG11-高级AI开发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>4</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=32218&keywords=python&tid=87&lid=2218">15851-后台开发工程师</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=32217&keywords=python&tid=87&lid=2218">15851-后台开发工程师</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a id="test" class="test" target='_blank' href="position_detail.php?id=34511&keywords=python&tid=87&lid=2218">SNG11-高级业务运维工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
    </tbody>
</table>
"""
soup = BeautifulSoup(html, 'lxml')
print(soup, type(soup))
# 获取所有的 tr 标签
trs = soup.find_all("tr")
for tr in trs:
    print(tr)
    print('*' * 30)
# 获取第二个 tr 标签
tr = soup.find_all('tr')[1]
print(tr)
# 排除第一个tr值(通过切片的方式)
jobMsg = soup.find_all('tr')[1:]
print(jobMsg)
# 获取所有的 class = even 的 tr 标签:
# trs = soup.find_all('tr', class_='even')  # class为关键字,不能直接用作变量名
trs = soup.find_all('tr', attrs={"class": "even"})  # 效果同上,如果有多个值,在后面添加即可,推荐
for tr in trs:
    print(tr)
    print('--' * 44)
# 获取所有a标签里面的 href 属性值:
allA = soup.find_all('a')
for a in allA:
    href = a.get('href')
    print(href)
# 获取所有的岗位信息
trs = soup.find_all('tr')[1:]   # 把第一个的表头去掉
# print(trs)
for tr in trs:
    tds = tr.find_all('td')   # 找到所有的 td
    jobName = tds[0].string   # 获取文本数据,如果数据狠多,可以使用strings
    print(jobName)

以上就是Python数据解析之BeautifulSoup4的用法详解的详细内容,更多关于Python BeautifulSoup4的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文