一、基本元素

BeautifulSoup库是解析、遍历、维护“标签树”的功能库。

引用

 from bs4 import BeautifulSoup
 import bs4

html文档-标签树-BeautifulSoup类

 from bs4 import BeautifulSoup
soup1 = BeautifulSoup(“<html>data</html>”,”html.parser”)
soup2 = BeautifulSoup(open(“D://demo.html”),”html.parser”)

一个BeautifulSoup对象对应一个HTML/XML文档的全部内容

 1 import requests
2 from bs4 import BeautifulSoup
r = requests.get("http://python123.io/ws/demo.html")
r.text
'<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\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:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>\r\n</body></html>'
demo = r.text
soup = BeautifulSoup(demo,"html.parser")
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>
30 .
</p>
</body>
</html>

在上述代码中,一个BeautifulSoup对象对应一个HTML文档的全部内容,可查看r,demo,soup的类型

 type(r)
<class 'requests.models.Response'>
type(demo)
<class 'str'>
type(soup)
<class 'bs4.BeautifulSoup'>

BeautifulSoup库解析器

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

BeautifulSoup类基本元素

基本元素 说明
Tag 标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾
Name 标签的名字,<p>…</p>的名字是’p’,格式:<tag>.name
Attributes 标签的属性,字典组织形式,格式:<tag>.attrs
NavigableString 标签内非属性字符串,<>…</>中字符串,格式:<tag>.string
Comment 标签内字符串的注释部分,一种特殊的Comment类型

以"http://python123.io/ws/demo.html"html文档为例,先生成soup对象(BeautifulSoup类),该文档的详细内容在※代码中可看到。

1 import requests
2 from bs4 import BeautifulSoup
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo,"html.parser")

1、soup的标题及标签

文档中有两个a标签,直接使用soup.a只可以获得第一个a标签

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

2、标签名

 soup.a.name #标签a的标签名
'a'
soup.a.parent.name #标签a的父标签名
'p'
soup.a.parent.parent.name #标签a的父标签的父标签名
'body'

3、标签属性

 tag = soup.a #tag为soup中的a标签
tag.attrs #标签属性值
{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
tag.attrs['class'] #标签'class'属性值
['py1']
tag.attrs['href'] #标签'href'属性值
'http://www.icourse163.org/course/BIT-268001'
type(tag.attrs) #标签属性类型
<class 'dict'>
type(tag) #标签类型
<class 'bs4.element.Tag'>

4、标签内非属性字符串

NavigableString可跨越多个层次,如下代码中p标签内还有b标签,但不会打印b标签,而是打印b标签内的字符串

 soup.a #标签a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
soup.a.string #标签a内非属性字符串
'Basic Python'
soup.p #标签p
<p class="title"><b>The demo python introduces several python courses.</b></p>
soup.p.string #标签p内非属性字符串
'The demo python introduces several python courses.'
type(soup.a.string) #标签a内非属性字符串类型
<class 'bs4.element.NavigableString'>
type(soup.p.string) #标签p内非属性字符串类型
<class 'bs4.element.NavigableString'>

5、标签内字符串的注释部分

使用<tag>.string时显示的字符串类型可能是NavigableString,也可能是Comment。

 newsoup = BeautifulSoup("<b><!-- This is a comment --></b><p>This is not a comment</p>","html.parser") #创建一个新的BeautifulSoup对象
newsoup.b.string #标签b的字符串
' This is a comment '
newsoup.p.string #标签p的字符串
'This is not a comment'
type(newsoup.b.string) #标签b的字符串类型
<class 'bs4.element.Comment'>
type(newsoup.p.string) #标签p的字符串类型
<class 'bs4.element.NavigableString'>

综上所述

<p class = "title">...</p>

标签 .<tag>

名称 .name

属性 .attrs

非属性字符串/注释 .string

 二、HTML内容的遍历方法

1、标签树的下行遍历

属性 说明
.contents 子节点的列表,将<tag>所有儿子节点存入列表
.children 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历

以※处的html文档为例

 import requests
from bs4 import BeautifulSoup
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo,"html.parser")

head标签、head标签儿子节点及body标签儿子节点

 soup.head #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) #body标签儿子节点数量
5
soup.body.contents[1] #body标签中的第二个儿子标签
<p class="title"><b>The demo python introduces several python courses.</b></p>

综上

遍历儿子节点

 for child in soup.body.children:
print(child)

遍历子孙节点

for descendant in soup.body.descendants
print(child)

2、标签树的上行遍历

属性 说明
.parent 节点的父亲标签
.parents 节点先辈标签的迭代类型,用于循环遍历先辈节点

同样的,以※处的html文档为例

 soup.title.parent #title的父标签
<head><title>This is a python demo page</title></head>
soup.html.parent #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>
soup.parent #soup的父标签

由以上代码可知,title标签的父标签为head标签,html标签是html文档的最高级标签,其父标签就是自己。soup是一种特殊的标签,其父标签为空。

标签树的上行遍历

 soup = BeautifulSoup(demo,"html.parser")
for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)

3、标签树的平行遍历

平行遍历发生在同一个父节点下的各节点间

属性 说明
.next_sibling 返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling 返回按照HTML文本顺序的上一个平行节点标签
.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签

同样的,以※处的html文档为例

 soup.a.next_sibling #标签a的后续平行节点
' and '
soup.a.next_sibling.next_sibling #标签a后续平行节点的后续平行节点
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
soup.a.previous_sibling #标签a的前续平行节点
'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 #标签a前续平行节点的前续平行节点(为空)
soup.a.parent #标签a的父亲节点
<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>

遍历后续节点

 for sibling in soup.a.next_siblings:
print(sibling)

遍历前续节点

 for sibling in soup.a.previous_siblings:
print(sibling)

三、HTML的格式化和编码

prettify()方法

以※处的html文档为例

 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>

编码方式为utf-8

资料来源:《Python网络爬虫与信息提取》——嵩天,北京理工大学,MOOC

Python中的BeautifulSoup库简要总结的更多相关文章

  1. 【归纳】正则表达式及Python中的正则库

    正则表达式 正则表达式30分钟入门教程 runoob正则式教程 正则表达式练习题集(附答案) 元字符\b代表单词的分界处,在英文中指空格,标点符号或换行 例子:\bhi\b可以用来匹配hi这个单词,且 ...

  2. python下载安装BeautifulSoup库

    python下载安装BeautifulSoup库 1.下载https://www.crummy.com/software/BeautifulSoup/bs4/download/4.5/ 2.解压到解压 ...

  3. 利用Python中的mock库对Python代码进行模拟测试

    这篇文章主要介绍了利用Python中的mock库对Python代码进行模拟测试,mock库自从Python3.3依赖成为了Python的内置库,本文也等于介绍了该库的用法,需要的朋友可以参考下     ...

  4. Python中使用第三方库xlrd来写入Excel文件示例

    Python中使用第三方库xlrd来写入Excel文件示例 这一篇文章就来介绍下,如何来写Excel,写Excel我们需要使用第三方库xlwt,和xlrd一样,xlrd表示read xls,xlwt表 ...

  5. 第14.12节 Python中使用BeautifulSoup解析http报文:使用select方法快速定位内容

    一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>和<第14.11节 Python中使用BeautifulSo ...

  6. 第14.11节 Python中使用BeautifulSoup解析http报文:使用查找方法快速定位内容

    一. 引言 在<第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问>介绍了BeautifulSoup对象的主要属性,通过这些属性可以访 ...

  7. 第14.10节 Python中使用BeautifulSoup解析http报文:html标签相关属性的访问

    一. 引言 在<第14.8节 Python中使用BeautifulSoup加载HTML报文>中介绍使用BeautifulSoup的安装.导入和创建对象的过程,本节介绍导入后利用Beauti ...

  8. 在Python中使用BeautifulSoup进行网页爬取

    目录 什么是网页抓取? 为什么我们要从互联网上抓取数据? 网站采集合法吗? HTTP请求/响应模型 创建网络爬虫 步骤1:浏览并检查网站/网页 步骤2:创建用户代理 步骤3:导入请求库 检查状态码 步 ...

  9. 第14.8节 Python中使用BeautifulSoup加载HTML报文

    一. 引言 BeautifulSoup是一个三方模块bs4中提供的进行HTML解析的类,可以认为是一个HTML解析工具箱,对HTML报文中的标签具有比较好的容错识别功能.阅读本节需要了解html相关的 ...

随机推荐

  1. python_4

    1.迭代器:通过iter()方法获得了list的迭代对象,然后就可以通过next()方法来访问list中的元素了,当容器中没有可访问元素时,会抛出StopIteration异常终止迭代器 data = ...

  2. django,模板继承常用标签和规则

    一.定义基础模板 在html内容中定义多个block块,block由子模板引用同名block块,来决定是否替换这些部分{% block title %}一些内容,这里可不填{% endblock %} ...

  3. [LC] 270. Closest Binary Search Tree Value

    Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...

  4. 进程异常行为-反弹Shell攻击,KILL多个进程

    进程异常行为-反弹Shell攻击 父进程名称:bash 进程名称:bash 进程名称:/usr/bin/bash 进程id:23,077 命令行参数:sh -c /bin/bash -i >&a ...

  5. iOS漂亮的Toolbar动画、仿美团主页、简易笔记本、流失布局、标签分组等源码

    iOS精选源码 JPLiquidLayout 简单易用的流式布局 labelGroupAndStreamSwift---标签分组,单选,多选 iOS采用UITableView和UIScrollView ...

  6. 树状数组 hdu2689 hdu2838

    题意:给定一个正整数n,和一个1-n的一个排列,每个数可以和旁边的两个数的任意一个交换,每交换一次总次数就要加一,问将这个排列转换成一个递增的排列需要多少次交换? 题意可以转换成求这个排列的逆序对数. ...

  7. python面向对象类的约束和设计的统一化规范

    .封装 定义:将一些东西内容封存到一个地方,你还可以再取出, 类设置静态属性,设置一些方法 对象可以在其对象空间中封装一些属性 2.多态 定义:一个事物的多种形态 就想a可以是一个字符串,可以是一个列 ...

  8. 点分治——POJ 1741

    写的第一道点分治的题目,权当认识点分治了. 点分治,就是对每条过某个点的路径进行考虑,若路径不经过此点,则可以对其子树进行考虑. 具体可以看menci的blog:点分治 来看一道例题:POJ 1741 ...

  9. linux系统开机静态分配ip地址

    在/etc/sysconfig/network-scripts/ifcfg-eth0文件中 添加: IPADDR=192.168.1.100(设置静态地址) NETMASK=255.255.255.0 ...

  10. PCIe的事务传输层的处理(TLP)

    主要从以下几个方面解决: 1.TLP基本的概念: 2.寻址定位与路由导向 3.请求和响应机制 4.虚拟通道机制 5.数据完整性 6.i/o,memory,configuration,message r ...