BeautifulSoup库

2023-11-18

BeautifulSoup安装

1、以管理员运行cmd
2、输入 pip install beautifulsoup4

BeautifulSoup库的基本元素

BeautifulSoup库的理解:BeautifulSoup库是解析、遍历、维护“标签树”的功能库
在这里插入图片描述

基本元素 说明
Tag 标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾
Name 标签的名字,< p >…< /p>的名字是‘p’,格式:< tag>.name
Attributes 标签的属性,字典形式组织,格式:< tag>.sttrs
NavigableString 标签内非属性字符串,<>…</>中字符串,格式:< tag>.string
comment 标签内字符串的注释部分,一种特殊的comment类型
  • 1、实例
    以https://python123.io/ws/demo.html为练习对象
    以下图为网页源码
    在这里插入图片描述
    1、打印title
from bs4 import BeautifulSoup
import requests


r = requests.get(r'https://python123.io/ws/demo.html')
demo = r.text
soup = BeautifulSoup(demo,"html.parser")
print(soup.title)

结果:
<title>This is a python demo page</title>

2、获取标签信息

from bs4 import BeautifulSoup
import requests


r = requests.get(r'https://python123.io/ws/demo.html')
demo = r.text
soup = BeautifulSoup(demo,"html.parser")
print(soup.a)   #获取a标签,当有多个a标签的时候,soup.a只会得到第一个a标签
print(soup.a.name)  #获取a标签的名字
print(soup.a.parent.name)  #获取a标签父级名字
print(soup.a.parent.parent.name) #获取a标签父级的父级的名字

结果:
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
a
p
body

3、获取标签的属性

from bs4 import BeautifulSoup
import requests

r = requests.get(r'https://python123.io/ws/demo.html')
demo = r.text
soup = BeautifulSoup(demo,"html.parser")
tag = soup.a
print(tag.attrs)

结果:
{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}

4、获取标签的NavigableString

from bs4 import BeautifulSoup
import requests


r = requests.get(r'https://python123.io/ws/demo.html')
demo = r.text
soup = BeautifulSoup(demo,"html.parser")
tag = soup.a
print(tag.string)

结果:
Basic Python

5、comment(暂有问题,需修改)

from bs4 import BeautifulSoup
import requests


soup = BeautifulSoup("<b><!--this is a comment--></b><p>this is not a comment</p>","html.parser")
tag = soup.b
print(tag.string)
print(type(tag))
tag1 = soup.p
print(tag1.string)
print(type(tag1))

结果:
this is a comment
<class 'bs4.element.Tag'>
this is not a comment
<class 'bs4.element.Tag'>

BeautifulSoup库的解析器

解析器 使用方法 条件
bs4的HTML解析器 BeautifulSoup(mk,“html.parser”) 安装bs4库
lxml的HTML解析器 BeautifulSoup(mk,“lxml”) pip install lxml
lxml的xml解析器 BeautifulSoup(mk,“xml”) pip install lxml
html5lib解析器 BeautifulSoup(mk,“html5lib”) pip install html5lib

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

在这里插入图片描述

  • 1、标签树的下行遍历
属性 说明
.contents 子节点的列表,将< tag>所有的儿子节点存入列表
.children 子节点的迭代类型,与 .contents类似,用于循环遍历儿子节点
.descendants 子孙节点的迭代类型,包含所有子孙节点(既一个节点后面所有的节点信息),用于循环遍历

练习:
1、获取子节点信息

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")
print(soup.body.contents)      #获取子节点信息
print(len(soup.body.contents))   #获取子节点的个数
print(soup.body.contents[1])    #通过坐标获取单个子节点

结果:
['\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']
5
<p class="title"><b>The demo python introduces several python courses.</b></p>

2、遍历

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")
# 遍历儿子节点
print(type(soup.body.children))
for chil in soup.body.children:
    print(chil)
#遍历子孙节点
for chil in soup.body.descendants:
    print(chil)
  • 2、标签树的上行遍历
属性 说明
.parent 子节点的父标签
.parents 节点先辈标签的迭代类型,用于循环遍历先辈节点

练习:
1、获取父节点

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")

print(soup.title.parent)

结果:
<head><title>This is a python demo page</title></head>

2、遍历父节点

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")

# 遍历先辈节点
for parent in soup.a.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)

结果:
p
body
html
[document]
  • 3、标签树的平行遍历
    平行遍历发生在同一个父节点下的各节点间
属性 说明
.next_sibling 返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling 返回按照HTML文本顺序的上一个平行节点标签
.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签

练习:
1、获取平行节点

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")

print(soup.a.next_sibling)   #由此可见,标签的平行标签不一定是一个标签
print(soup.a.next_sibling.next_sibling)
print(soup.a.previous_sibling)

结果:
 and 
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:

2、遍历

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")

# 遍历后续节点
for sibling in soup.a.next_siblings:
    print(sibling)
# 遍历前续节点
for sibling in soup.a.previous_siblings:
    print(sibling)

基于bs64库的HTML格式化和编码

格式化:bs4库的prettify()方法

import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")

print(soup)
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>


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

由结果可以看得出来,使用prettify()方法之后,他在每个标签的后面都加了换行符/n,使结果更加美化的展示出来

信息标记

信息标记的三种方式:

  • 1、xml


在这里插入图片描述
在这里插入图片描述

  • 2、json
    在这里插入图片描述
    在这里插入图片描述
  • 3、yaml
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

三种信息标记形式的比较:
XML:
1、最早的通用信息标记语言,可扩展性好,但繁琐
2、Internet上的信息交互与传递
json:
1、信息有类型,适合程序处理(js),较xml简洁
2、移动应用云端和节点的信息通信,无注释
YAML:
1、信息无类型,文本信息比例最高,可读性好
2、各类系统的配置文件,有注释易读

基于bs4库的HTML内容查找方法

<>.find_all(name,attrs,recursive,string,**kwargs)
返回一个列表类型,存储查找的结果
name:对标签名称的检索字符串
例:

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")


print(soup.find_all("a"))  #也可以使用正则获取包含a的

attrs:对标签属性值的检索字符串,可标注属性检索

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")


print(soup.find_all("p","course"))  #查询p标签中包含course的值

recursive:是否对子孙全部检索,默认为True

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")


print(soup.find_all("p",recursive=False))  

string:<>…</>中字符串区域的检索字符串

from bs4 import BeautifulSoup
import requests

url = "https://python123.io/ws/demo.html"
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo,"html.parser")


print(soup.find_all(string="Basic Python"))  
扩展方法
方法 说明
<>.find() 搜索且只返回一个结果,字符串类型,同find_all()参数
<>.find_parents() 在先辈节点中搜索,返回列表类型,同.find_all()参数
<>.find_parent() 在先辈节点中返回一个结果,字符串类型,同.find_all()参数
<>.find_next_siblings() 在后续平行节点中搜索,返回列表类型,同.find_all()参数
<>.find_next_sibling() 在后续平行节点中返回一个结果,字符串类型,同.find_all()参数
<>.find_previous_siblings() 在前续平行节点中搜索,返回列表类型,同.find_all()参数
<>.find_previous_sibling() 在前续平行节点中返回一个结果,字符串类型,同.find_all()参数
  • 1、实例1,在最好大学网获取前20的大学排名
from bs4 import BeautifulSoup
import requests
import bs4

def get_url(url):
    try:
        r = requests.get(url,timeout= 30)
        r.raise_for_status()   #产生异常信息
        r.encoding = r.apparent_encoding   #修改编码
        return r.text
    except:
        return ""
    return ""

def get_txt(ulist,html):
    soup = BeautifulSoup(html,"html.parser")
    for tr in soup.find("tbody").children:
        if isinstance(tr,bs4.element.Tag):   #过滤不是bs4.element.Tag标签
            tds = tr("td")  #查询所有的td标签
            ulist.append([tds[0].string,tds[1].string,tds[3].string])


def print_txt(ulist,num):
    tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
    #{1:{3}^10} 1表示位置,{3}表示用第3个参数来填充,从0开始算,^表示居中,10表示占10个位置
    # https://blog.csdn.net/james_616/article/details/79004482,关于format的介绍
    # chr(12288) 中文空格
    print(tplt.format("排名","学校名称","总分",chr(12288)))
    for i in range(num):
        u = ulist[i]
        print(tplt.format(u[0],u[1],u[2],chr(12288)))
def main():
    uinfo = []
    url = "http://www.zuihaodaxue.com/zuihaodaxuepaiming2018.html"
    html = get_url(url)
    get_txt(uinfo,html)
    print_txt(uinfo,20)  #打印前20

main()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

BeautifulSoup库 的相关文章

随机推荐

  • 实验五:LINUX 下C语言使用、编译与调试实验

    实验五 LINUX 下C语言使用 编译与调试实验 一 实验目的 练习并掌握Linux提供的vi编辑器来编译C程序 学会利用gcc gdb编译 调试C程序 学会使用make工具 二 实验内容 编写C语言程序 用gcc编译并观察编译后的结果 运
  • 接口的加密解密

    接口加密 1 接口参数加密 基础加密 2 接口参数加密 接口时效性验证 一般达到这个级别已经非常安全了 3 接口参数加密 时效性验证 私钥 达到这个级别安全性固若金汤 4 接口参数加密 时效性验证 私钥 Https 我把这个级别称之为金钟罩
  • iOS进阶_NSURLSession(二.断点续传)

    断点续传 从上一篇文章中 我们了解了使用NSURLSession进行文件下载 我们在其基础上继续探索NSURLSession的断点续传 在NSURLSession中 我们使用reumeData来存储下载的数据进度 import ViewCo
  • kali linux 报告工具集 faraday 忘记密码处理办法

    kali linux 报告工具集 faraday 忘记密码处理办法 第一步 切换到root 用户 执行命令 su root 第二步停止数据库服务 systemctl stop postgresql service 第三步重新启动数据库 sy
  • KMP 算法

    KMP 算法的核心是利用匹配失败后的信息 尽量减少模式串与主串的匹配次数以达到快速的匹配的目的 具体实现是通过一个next 函数来实现的 函数本身包含了模式串的局部匹配信息 KMP算法的时间复杂度O m n KMP 和 BF 唯一不一样的地
  • Pycharm如何配置解释器

    问题 安装Pycharm了就可以直接运行程序了吗 回答 不能 PyCharm是一种Python IDE 带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具 比如调试 语法高亮 Project管理 代码跳转 智能提示 自动完成
  • python-自定义函数(定义调用、默认参数、返回值)

    python 自定义函数 文章目录 python 自定义函数 初识函数 函数的定义与调用 函数的定义 参数列表 函数体 函数调用 默认参数 定义默认参数 默认参数的使用 默认参数的位置 默认参数为可变对象 默认参数为None 关键字参数传递
  • Linux系统管理-audit文件太多导致du -sh命令卡死

    1 问题现象 今日查询数据库文件系统的使用情况发现如下情况 du sh 卡死 进去下基层目录使用du sh 均未出现问题 2 问题分析 而在audit文件目录中使用du sh 命令时命令卡死 发现问题所在 使用ls查看audit目录的文件也
  • zsh: bad CPU type in executable: /usr/local/bin/git

    MAC安装nvm的时候报错zsh bad CPU type in executable usr local bin git 查找原因 通过where git可以看到有2个路径 一个 usr bin git一个 usr bin local g
  • 虚拟机--无法连接网络

    情况 运行命令 ifconfig 没有看到 ens33 网络 命令 ifconfig a 可以看到 ens33 其他 关闭防火墙 systemctl stop firewalld 查看状态 systemctl status firewall
  • HIT软件构造《设计模式》部分总结

    创造模式 创造模式关心的是对象类创造的过程应该遵循的原则 里氏替换原则 继承必须确保超类所拥有的性质在子类中仍然成立 里氏替换原则 Liskov Substitution Principle LSP 是面向对象的设计原则 通俗地讲 它指出了
  • 我放弃了VMware

    文章目录 哈哈哈 不得不说 有点儿标题狗的意思 不去写新闻真的屈才了 正如标题所说 我弃用了VMware 但是我使用上了WSL2 相对来说 wsl2使我不怎么担心我16G的内存不够用 其实 wsl也是虚拟技术的一种 但是相比VMware v
  • net start mysql80拒绝访问

    文章目录 1 问题描述 2 一次性解决方案 3 永久性解决方案 1 问题描述 问题描述 在我们使用dos窗口进行操作的时候 无论使用的是net start stop mysql80都会发生拒绝访问的问题 通常这个问题的发生都是因为大家把my
  • 国产信创服务器如何进行安全可靠的文件传输?

    信创 即信息技术应用创新 2018年以来 受 华为 中兴事件 影响 国家将信创产业纳入国家战略 并提出了 2 8 n 发展体系 从产业链角度 信创产业生态体系较为庞大 主要包括基础硬件 基础软件 应用软件 信息安全4部分构成 其中芯片 服务
  • ChatGPT知多少?小白扫盲,通俗易懂

    一 ChatGPT到底是什么 ChatGPT是由OpenAI 发布的自然语言模型 它的英文全称是 Chat Generative Pre trained Transformer 直译过来就是作为聊天使用的生成式预训练转换器 其中 Chat代
  • 此时不应有java_Java出现"此时不应有......."的错误

    今晚在安装weblogic的时候 双击运行startWebLogic cmd dos窗口一闪而过 随后将 startWebLogic cmd 拖进cmd窗口运行 显示 此时不应有 tools jar 然后我把环境变量CLASSPATH中的
  • H265视频转码H264视频

    LiveMedia视频平台提供H5网页web前端无插件视频码流 但目前主流浏览器和播放器都只支持H264的码流 但是随着编码技术的迭代 目前H265编码的视频已在安防行业得到了广泛的使用 平台仅支持H264需要客户修改前端的视频编码 这样会
  • html动态标题设计源码

    html酷炫动态发光标题 效果图如下 index html
  • 【spring boot logback】日志颜色渲染,使用logback-spring.xml自定义的配置文件后,日志没有颜色了...

    接着spring boot日志logback解析之后 发现使用logback spring xml自定义的配置文件后 日志没有颜色了 怎么办 官网处理日志链接 https logback qos ch manual layouts html
  • BeautifulSoup库

    BeautifulSoup安装 1 以管理员运行cmd 2 输入 pip install beautifulsoup4 BeautifulSoup库的基本元素 BeautifulSoup库的理解 BeautifulSoup库是解析 遍历 维