学习笔记——Beautiful Soup库的安装与基本使用方法_beautifulsoup库怎么安装-程序员宅基地

技术标签: 爬虫  bs4基本使用方法  Beautifu Soup库  

一、Beautiful Soup库的安装

Beautifu Soup库一个非常优秀的Python第三方库,可以很好地对HTML进行解析并且提取其中的信息。主要负责解析、遍历、维护“标签树”。

1. 安装过程很简单,如下:

以管理员命令运行cmd=>pip install beautifulsoup4
这里注意后面有个4,这是最新的版本。详细可以参考Beautiful Soup的官网

2. 测试

>>> import requests
>>> r = requests.get('http://python123.io/ws/demo.html')
>>> r.text
'...`  # 这里省略了内容
>>> demo = r.text
>>> from bs4 import BeautifulSoup # 这个导入需要注意
>>> soup = BeautifulSoup(demo,'html.parser')  # 可以用help(BeautifulSop)查看帮助文档
>>> print(soup.prettify())
`...` # 这里省略了内容

二、Beautiful Soup库的基本元素

1. Beautiful Soup库的理解

Beautiful Soup库就是一个工具,可以从被标记的信息中识别出来标记信息,从而精准的提取你需要的信息。
在这里插入图片描述
在这里插入图片描述

2. Beautiful Soup库的的导入

Beautiful Soup库,也叫beautifulsoup4 或bs4,约定引用方式如下,即主要是用BeautifulSoup类

# 第一种用的最为频繁
from bs4 import BeautifulSoup
# 第二种
import bs4

3. Beautiful Soup库的解析器

BeautifulSoup类,BeautifulSoup对应一个HTML/XML文档的全部内容。
在这里插入图片描述

4. BeautifulSoup类的基本元素

在这里插入图片描述
在这里插入图片描述
接着测试文档实践

1. tag——标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾。

任何存在于HTML语法中的标签都可以用soup.访问获得,当HTML文档中存在多个相同对应内容时,soup.返回第一个。

>>> soup.title
<title>This is a python demo page</title>
>>> tag = soup.a
>>> print(tag)
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>

2. Name——标签的名字,<p…/p>的名字是’p’,格式:.name

每个tag都有自己的名字,通过.name获取,字符串类型。

>>> soup.a.name
'a'
>>> soup.a.parent.name
'p'
>>> soup.a.parent.parent.name
'body'

3. Attrs——标签的属性,字典形式组织,格式:.attrs

一个可以有0或多个属性,返回一个字典,属于字典类型。

>>> tag = soup.a
>>> tag.attrs
{
    'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
>>> tag.attrs['class'] # 根据字典的键,获取相应的值
['py1']
>>> tag.attrs['href']
'http://www.icourse163.org/course/BIT-268001'
>>> type(tag.attrs) # 查看属性类型
<class 'dict'>
>>> type(tag)
<class 'bs4.element.Tag'>

4. NavigableString——标签内非属性字符串,<>…</>中字符串,格式:.string

NavigableString可以跨越多个层次,前提是只有一个字符串子串,多余一个子串则也返回None.
help文档里面解释是:
string
| Convenience property to get the single string within this tag.
|
| :Return: If this tag has a single string child, return value
| is that string. If this tag has no children, or more than one
| child, return value is None. If this tag has one child tag,
| return value is the ‘string’ attribute of the child tag,
| recursively.

>>> soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> soup.a.string
'Basic Python'
>>> soup.p # 可以跨越多个层次
<p class="title"><b>The demo python introduces several python courses.</b></p>
>>> soup.p.string
'The demo python introduces several python courses.'
>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>

5. Comment——标签内字符串的注释部分,一种特殊的Comment类型

Comment是一种特殊类型。

>>> newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</P>","html.parser")
>>> newsoup.b.string
'This is a comment'
>>> type(newsoup.b.string)
<class 'bs4.element.Comment'> # 注释类型
>>> newsoup.p.string
'This is not a comment'
>>> type(newsoup.p.string)
<class 'bs4.element.NavigableString'> # 非注释的字符串类型

6. text——返回标签所有字符串子串,使用给定的分隔符连接

官方help文档,常与字符串的split()方法联用来分割得到需要的部分。
text
| Get all child strings, concatenated using the given separator.

>>> soup.h1.text
        
'\n\n 中国中车 (601766)\n \n已收盘 2019-01-23 \xa015:01:28\n \n'

三、基于bs4库的HTML内容三种遍历方法

基于bs4库的HTML内容遍历方法主要分为三种:下行遍历、上行遍历、平行遍历。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1. 标签树的下行遍历

标签树的下行遍历的三个属性:

  1. .contents——子节点的列表,将所有儿子节点存入列表
  2. .children 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
  3. .descendants 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历
    主要用到的两种遍历形式:
# 遍历儿子节点
for child in soup.body.children:
    print(child)
# 遍历子孙节点
for child in soup.body.descendants:
    print(child)

实例演示:

>>> soup.head # 查看标签
<head><title>This is a python demo page</title></head>
>>> soup.head.contents # 查看head标签的内容,注意这里返回的是一个列表,所以可以对返回到列表执行列表操作
[<title>This is a python demo page</title>]
>>> soup.body.contents # 获得body标签的内容列表
['\n', <p class="title"><b>The demo python introduces several python courses.</b></p>, '\n', <p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>, '\n']
>>> len(soup.body.contents) # 获取列表的元素个数,注意这里的'\n'也算一个元素
5
>>> soup.body.contents[1] # 查看列表的第二个元素
<p class="title"><b>The demo python introduces several python courses.</b></p>

2. 标签树的上行遍历

标签树的上行遍历主要包含两个属性:

  1. .parent 节点的父亲标签
  2. .parents 节点先辈标签的迭代类型,用于循环遍历先辈节点
    实例如下:
>>> soup.title.parent
<head><title>This is a python demo page</title></head>
>>> soup.html.parent
<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:

<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>
</body></html>
>>> soup.parent # soup的父亲是空的
# 对Soup.a标签的所有父辈标签名字进行打印
>>> for parent in soup.a.parents: # 标签树的上行代码遍历
             if parent is None: # 因为会遍历到最上面的soup,但是soup没有标签名,所以要区分对待
                  print(parent)
else:
                  print(parent.name)

  
p
body
html
[document]

3. 标签树的平行遍历

标签树的平行遍历有四个属性:

  1. .next_sibling 返回按照HTML文本顺序的下一个平行节点标签,有可能得到的是NavigableString,所以后续需要做判断
  2. .previous_sibling 返回按照HTML文本顺序的上一个平行节点标签,有可能得到的是NavigableString,所以后续需要做判断
  3. .next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
  4. .previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签
    在这里插入图片描述
    主要使用方法:
# 遍历后续平行节点
for sibling in soup.a.next_sibling:
    print(sibling)
# 遍历前续平行节点
for sibling in soup.a.previous_sibling:
    print(sibling)

实例:

>>> soup.a.next_sibling # 注意这里得到的不是标签,而是字符串,所以需要做判断处理
' and '
>>> soup.a.next_sibling.next_sibling
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
>>> soup.a.previous_sibling
'Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n'
>>> soup.a.previous_sibling.previous_sibling
>>> soup.a.parent
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:

<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>

4. 小结

在这里插入图片描述

四、prettify()和find_all()方法

1. prettify()方法

prettify()方法能够让HTML的内容更加友好的显示出来便于我们分析网页,从而发现规律。
.prettify()为HTML文本<>及其内容增加’\n’
.prettify()可用于标签,方法:.prettify()
bs4库将任何HTML输入都变成utf‐8编码
Python 3.x默认支持编码是utf‐8,解析无障碍
实例如下:

>>> soup.prettify()
'<html>\n <head>\n <title>\n This is a python demo page\n </title>\n </head>\n <body>\n <p class="title">\n <b>\n The demo python introduces several python courses.\n </b>\n </p>\n <p class="course">\n Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">\n Basic Python\n </a>\n and\n <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">\n Advanced Python\n </a>\n .\n </p>\n </body>\n</html>'
>>> print(soup.prettify())
<html>
 <head>
  <title>
   This is a python demo page
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    The demo python introduces several python courses.
   </b>
  </p>
  <p class="course">
   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
    Basic Python
   </a>
   and
   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
    Advanced Python
   </a>
   .
  </p>
 </body>
</html>

2. <>.find_all()方法

<>.find_all(name, attrs, recursive, string, **kwargs)——返回一个列表类型,存储查找的结果

  1. name : 对标签名称的检索字符串
  2. attrs: 对标签属性值的检索字符串,可标注属性检索
  3. recursive: 是否对子孙全部检索,默认True
  4. string: <>…</>中字符串区域的检索字符串
# 1. name: 对标签名称的检索字符串
>>> soup.find_all('a') # 注意返回的是一个列表
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all(['a','b']) # 传入一个列表,实现同时检索出列表里面两个或者多个标签的内容
[<b>The demo python introduces several python courses.</b>, <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> for tag in soup.find_all(True):
 print(tag.name)

	
html
head
title
body
p
b
p
a
a
# 实现同时检索出b标签和包含b字符的body标签,需要引入正则表达式re模块
>>> import re
>>> for tag in soup.find_all(re.compile('b')):
 print(tag.name)

	
body
b
# 2. attrs: 对标签属性值的检索字符串,可标注属性检索
>>> soup.find_all('p','course') 
[<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>]
>>> soup.find_all(id = 'link1')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>]
>>> soup.find_all(id='link') # 需要完全匹配,所以匹配不到link,返回空列表
[]
>>> soup.find_all(id=re.compile('link'))  # 通过正则表达式实现部分匹配
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
# 3. recursive: 是否对子孙全部检索,默认True
>>> soup.find_all('a') # 返回包括子孙节点在内的所有‘a'标签的内容,下面是查到到两个
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all('a',recursive=False) # 可以看到在soup这个平行节点中,没有找到a标签,所以a标签在soup的子孙节点
[]
# 4. string: <>…</>中字符串区域的检索字符串
>>> soup.find_all(string = 'Basic Python') # 完全匹配检索Basic Python
['Basic Python']
>>> soup.find_all(string = re.compile("python")) # 使用re模块的正则表达式实现部分匹配,所以re和find_all()结合使用,功能强大
['This is a python demo page', 'The demo python introduces several python courses.']

注意:
(…) 等价于.find_all(…)
soup(…) 等价于soup.find_all(…)
扩展方法:

  1. <>.find() 搜索且只返回一个结果,同.find_all()参数
  2. <>.find_parents() 在先辈节点中搜索,返回列表类型,同.find_all()参数
  3. <>.find_parent() 在先辈节点中返回一个结果,同.find()参数
  4. <>.find_next_siblings() 在后续平行节点中搜索,返回列表类型,同.find_all()参数
  5. <>.find_next_sibling() 在后续平行节点中返回一个结果,同.find()参数
  6. <>.find_previous_siblings() 在前序平行节点中搜索,返回列表类型,同.find_all()参数
  7. <>.find_previous_sibling() 在前序平行节点中返回一个结果,同.find()参数

五、参考资料

北京理工大学嵩天老师的《Python网络爬虫与信息提取》

后记:
我从本硕药学零基础转行计算机,自学路上,走过很多弯路,也庆幸自己喜欢记笔记,把知识点进行总结,帮助自己成功实现转行。
2020下半年进入职场,深感自己的不足,所以2021年给自己定了个计划,每日学一技,日积月累,厚积薄发。
如果你想和我一起交流学习,欢迎大家关注我的微信公众号每日学一技,扫描下方二维码或者搜索每日学一技关注。
这个公众号主要是分享和记录自己每日的技术学习,不定期整理子类分享,主要涉及 C – > Python – > Java,计算机基础知识,机器学习,职场技能等,简单说就是一句话,成长的见证!
每日学一技

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_27283619/article/details/86589666

智能推荐

前端开发之vue-grid-layout的使用和实例-程序员宅基地

文章浏览阅读1.1w次,点赞7次,收藏34次。vue-grid-layout的使用、实例、遇到的问题和解决方案_vue-grid-layout

Power Apps-上传附件控件_powerapps点击按钮上传附件-程序员宅基地

文章浏览阅读218次。然后连接一个数据源,就会在下面自动产生一个添加附件的组件。把这个控件复制粘贴到页面里,就可以单独使用来上传了。插入一个“编辑”窗体。_powerapps点击按钮上传附件

C++ 面向对象(Object-Oriented)的特征 & 构造函数& 析构函数_"object(cnofd[\"ofdrender\"])十条"-程序员宅基地

文章浏览阅读264次。(1) Abstraction (抽象)(2) Polymorphism (多态)(3) Inheritance (继承)(4) Encapsulation (封装)_"object(cnofd[\"ofdrender\"])十条"

修改node_modules源码,并保存,使用patch-package打补丁,git提交代码后,所有人可以用到修改后的_修改 node_modules-程序员宅基地

文章浏览阅读133次。删除node_modules,重新npm install看是否成功。在 package.json 文件中的 scripts 中加入。修改你的第三方库的bug等。然后目录会多出一个目录文件。_修改 node_modules

【】kali--password:su的 Authentication failure问题,&sudo passwd root输入密码时Sorry, try again._password: su: authentication failure-程序员宅基地

文章浏览阅读883次。【代码】【】kali--password:su的 Authentication failure问题,&sudo passwd root输入密码时Sorry, try again._password: su: authentication failure

整理5个优秀的微信小程序开源项目_微信小程序开源模板-程序员宅基地

文章浏览阅读1w次,点赞13次,收藏97次。整理5个优秀的微信小程序开源项目。收集了微信小程序开发过程中会使用到的资料、问题以及第三方组件库。_微信小程序开源模板

随便推点

Centos7最简搭建NFS服务器_centos7 搭建nfs server-程序员宅基地

文章浏览阅读128次。Centos7最简搭建NFS服务器_centos7 搭建nfs server

Springboot整合Mybatis-Plus使用总结(mybatis 坑补充)_mybaitis-plus ruledataobjectattributemapper' and '-程序员宅基地

文章浏览阅读1.2k次,点赞2次,收藏3次。前言mybatis在持久层框架中还是比较火的,一般项目都是基于ssm。虽然mybatis可以直接在xml中通过SQL语句操作数据库,很是灵活。但正其操作都要通过SQL语句进行,就必须写大量的xml文件,很是麻烦。mybatis-plus就很好的解决了这个问题。..._mybaitis-plus ruledataobjectattributemapper' and 'com.picc.rule.management.d

EECE 1080C / Programming for ECESummer 2022 Laboratory 4: Global Functions Practice_eece1080c-程序员宅基地

文章浏览阅读325次。EECE 1080C / Programming for ECESummer 2022Laboratory 4: Global Functions PracticePlagiarism will not be tolerated:Topics covered:function creation and call statements (emphasis on global functions)Objective:To practice program development b_eece1080c

洛谷p4777 【模板】扩展中国剩余定理-程序员宅基地

文章浏览阅读53次。被同机房早就1年前就学过的东西我现在才学,wtcl。设要求的数为\(x\)。设当前处理到第\(k\)个同余式,设\(M = LCM ^ {k - 1} _ {i - 1}\) ,前\(k - 1\)个的通解就是\(x + i * M\)。那么其实第\(k\)个来说,其实就是求一个\(y\)使得\(x + y * M ≡ a_k(mod b_k)\)转化一下就是\(y * M ...

android 退出应用没有走ondestory方法,[Android基础论]为何Activity退出之后,系统没有调用onDestroy方法?...-程序员宅基地

文章浏览阅读1.3k次。首先,问题是如何出现的?晚上复查代码,发现一个activity没有调用自己的ondestroy方法我表示非常的费解,于是我检查了下代码。发现再finish代码之后接了如下代码finish();System.exit(0);//这就是罪魁祸首为什么这样写会出现问题System.exit(0);////看一下函数的原型public static void exit (int code)//Added ..._android 手动杀死app,activity不执行ondestroy

SylixOS快问快答_select函数 导致堆栈溢出 sylixos-程序员宅基地

文章浏览阅读894次。Q: SylixOS 版权是什么形式, 是否分为<开发版税>和<运行时版税>.A: SylixOS 是开源并免费的操作系统, 支持 BSD/GPL 协议(GPL 版本暂未确定). 没有任何的运行时版税. 您可以用她来做任何 您喜欢做的项目. 也可以修改 SylixOS 的源代码, 不需要支付任何费用. 当然笔者希望您可以将使用 SylixOS 开发的项目 (不需要开源)或对 SylixOS 源码的修改及时告知笔者.需要指出: SylixOS 本身仅是笔者用来提升自己水平而开发的_select函数 导致堆栈溢出 sylixos

推荐文章

热门文章

相关标签