BeautifulSoup的基本使用

✅作者简介:大家好我是hacker707,大家可以叫我hacker
📃个人主页:hacker707的csdn博客
🔥系列专栏:python爬虫
💬推荐一款模拟面试、刷题神器👉点击跳转进入网站

BeautifulSoup的基本使用

bs4

; bs4的安装

要使用BeautifulSoup4需要先安装lxml,再安装bs4

pip install lxml
pip install bs4

使用方法:

from bs4 import BeautifulSoup

lxml和bs4对比学习

from lxml import etree
tree = etree.HTML(html)
tree.xpath()
from bs4 import BeautifulSoup
soup =  BeautifulSoup(html_doc, 'lxml')

注意事项:
创建soup对象时如果不传’lxml’或者features=”lxml”会出现以下警告

BeautifulSoup的基本使用

bs4的快速入门

解析器的比较(了解即可)

解析器用法优点缺点python标准库BeautifulSoup(markup,’html.parser’)python标准库,执行速度适中(在python2.7.3或3.2.2之前的版本中)文档容错能力差lxml的HTML解析器BeautifulSoup(markup,’lxml’)速度快,文档容错能力强需要安装c语言库lxml的XML解析器BeautifulSoup(markup,’lxml-xml’)或者BeautifulSoup(markup,’xml’)速度快,唯一支持XML的解析器需要安装c语言库html5libBeautifulSoup(markup,’html5lib’)最好的容错性,以浏览器的方式解析文档,生成HTML5格式的文档速度慢,不依赖外部扩展

对象种类

Tag:标签
BeautifulSoup:bs对象
NavigableString:可导航的字符串
Comment:注释

from bs4 import BeautifulSoup

html_doc = """
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;
and they lived at the bottom of a well.

...

"""

soup = BeautifulSoup(html_doc, 'lxml')
print(type(soup.title))
print(type(soup))
print(type(soup.title.string))
print(type(soup.span.string))

bs4的简单使用

获取标签内容

from bs4 import BeautifulSoup

html_doc = """
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;
and they lived at the bottom of a well.

...

"""

soup = BeautifulSoup(html_doc, 'lxml')
print('head标签内容:\n', soup.head)
print('body标签内容:\n', soup.body)
print('html标签内容:\n', soup.html)
print('p标签内容:\n', soup.p)

✅注意:在打印p标签对应的代码时,可以发现只打印了第一个p标签内容,这时我们可以通过find_all来获取p标签全部内容

print('p标签内容:\n', soup.find_all('p'))

✅这里需要注意使用find_all里面必须传入的是字符串
获取标签名字
通过name属性获取标签名字

from bs4 import BeautifulSoup

html_doc = """
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;
and they lived at the bottom of a well.

...

"""

soup = BeautifulSoup(html_doc, 'lxml')
print('head标签名字:\n', soup.head.name)
print('body标签名字:\n', soup.body.name)
print('html标签名字:\n', soup.html.name)
print('p标签名字:\n', soup.find_all('p').name)

✅如果要找到两个标签的内容,需要传入列表过滤器,而不是字符串过滤器
使用字符串过滤器获取多个标签内容会返回空列表

print(soup.find_all('title', 'p'))
[]

需要使用列表过滤器获取多个标签内容

print(soup.find_all(['title', 'p']))
[<title>The Dormouse's story, 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>]

获取a标签的href属性值

from bs4 import BeautifulSoup

html_doc = """
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;
and they lived at the bottom of a well.

...

"""

soup = BeautifulSoup(html_doc, 'lxml')
a_list = soup.find_all('a')

for a in a_list:

    print(a.get('href'))

    print(a.attrs['href'])

    print(a['href'])

✅扩展:使用prettify()美化 让节点层级关系更加明显 方便分析

print(soup.prettify())

不使用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>

使用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>

遍历文档树

from bs4 import BeautifulSoup

html_doc = """
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;
and they lived at the bottom of a well.

...

"""
soup = BeautifulSoup(html_doc, 'lxml')
head = soup.head

print(head.contents)

print(head.children)

for h in head.children:
    print(h)
html = soup.html

print(html.descendants)

for h in html.descendants:
    print(h)

'''
需要重点掌握的
string获取标签里面的内容
strings 返回是一个生成器对象用过来获取多个标签内容
stripped_strings 和strings基本一致 但是它可以把多余的空格去掉
'''
print(soup.title.string)
print(soup.html.string)

print(soup.html.strings)
for h in soup.html.strings:
    print(h)

print(soup.html.stripped_strings)
for h in soup.html.stripped_strings:
    print(h)
'''
parent直接获得父节点
parents获取所有的父节点
'''
title = soup.title

print(title.parent)

print(title.parents)
for p in title.parents:
    print(p)

print(soup.html.parent)

print(type(soup.html.parent))
案例练习

获取所有职位名称

html = """

            职位名称
            职位类别
            人数
            地点
            发布时间

            22989-金融云区块链高级研发工程师(深圳)
            技术类
            1
            深圳
            2017-11-25

            22989-金融云高级后台开发
            技术类
            2
            深圳
            2017-11-25

            SNG16-腾讯音乐运营开发工程师(深圳)
            技术类
            2
            深圳
            2017-11-25

            SNG16-腾讯音乐业务运维工程师(深圳)
            技术类
            1
            深圳
            2017-11-25

            TEG03-高级研发工程师(深圳)
            技术类
            1
            深圳
            2017-11-24

            TEG03-高级图像算法研发工程师(深圳)
            技术类
            1
            深圳
            2017-11-24

            TEG11-高级AI开发工程师(深圳)
            技术类
            4
            深圳
            2017-11-24

            15851-后台开发工程师
            技术类
            1
            深圳
            2017-11-24

            15851-后台开发工程师
            技术类
            1
            深圳
            2017-11-24

            SNG11-高级业务运维工程师(深圳)
            技术类
            1
            深圳
            2017-11-24

"""
思路

不难看出想要的数据在tr节点的a标签里,只需要遍历所有的tr节点,从遍历出来的tr节点取a标签里面的文本数据

代码实现
from bs4 import BeautifulSoup

html = """

            职位名称
            职位类别
            人数
            地点
            发布时间

            22989-金融云区块链高级研发工程师(深圳)
            技术类
            1
            深圳
            2017-11-25

            22989-金融云高级后台开发
            技术类
            2
            深圳
            2017-11-25

            SNG16-腾讯音乐运营开发工程师(深圳)
            技术类
            2
            深圳
            2017-11-25

            SNG16-腾讯音乐业务运维工程师(深圳)
            技术类
            1
            深圳
            2017-11-25

            TEG03-高级研发工程师(深圳)
            技术类
            1
            深圳
            2017-11-24

            TEG03-高级图像算法研发工程师(深圳)
            技术类
            1
            深圳
            2017-11-24

            TEG11-高级AI开发工程师(深圳)
            技术类
            4
            深圳
            2017-11-24

            15851-后台开发工程师
            技术类
            1
            深圳
            2017-11-24

            15851-后台开发工程师
            技术类
            1
            深圳
            2017-11-24

            SNG11-高级业务运维工程师(深圳)
            技术类
            1
            深圳
            2017-11-24

"""

soup = BeautifulSoup(html, 'lxml')

tr_list = soup.find_all('tr')[1:]

for tr in tr_list:
    a_list = tr.find_all('a')
    print(a_list[0].string)

运行结果如下:

22989-金融云区块链高级研发工程师(深圳)
22989-金融云高级后台开发
SNG16-腾讯音乐运营开发工程师(深圳)
SNG16-腾讯音乐业务运维工程师(深圳)
TEG03-高级研发工程师(深圳)
TEG03-高级图像算法研发工程师(深圳)
TEG11-高级AI开发工程师(深圳)
15851-后台开发工程师
15851-后台开发工程师
SNG11-高级业务运维工程师(深圳)

🔥以上就是bs4的基本使用,如果有改进的建议,欢迎在评论区留言奥~

BeautifulSoup的基本使用

Original: https://blog.csdn.net/xqe777/article/details/123588660
Author: honker707
Title: BeautifulSoup的基本使用

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/668814/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球