护肤品网站优化案例,有那个网站可以做食品台账,我的家乡湛江网站设计,做团队网站源码有哪些爬虫专栏#xff1a;http://t.csdnimg.cn/WfCSx
使用 Beautiful Soup
前面介绍了正则表达式的相关用法#xff0c;但是一旦正则表达式写的有问题#xff0c;得到的可能就不是我们想要的结果了。而且对于一个网页来说#xff0c;都有一定的特殊结构和层级关系#xff0c;… 爬虫专栏http://t.csdnimg.cn/WfCSx
使用 Beautiful Soup
前面介绍了正则表达式的相关用法但是一旦正则表达式写的有问题得到的可能就不是我们想要的结果了。而且对于一个网页来说都有一定的特殊结构和层级关系而且很多节点都有 id 或 class 来作区分所以借助它们的结构和属性来提取不也可以吗
这一节中我们就来介绍一个强大的解析工具 Beautiful Soup它借助网页的结构和属性等特性来解析网页。有了它我们不用再去写一些复杂的正则表达式只需要简单的几条语句就可以完成网页中某个元素的提取。
废话不多说接下来就来感受一下 Beautiful Soup 的强大之处吧。
1. Beautiful Soup 简介
简单来说BeautifulSoup 就是 Python 的一个 HTML 或 XML 的解析库我们可以用它来方便地从网页中提取数据官方的解释如下 BeautifulSoup 提供一些简单的、Python 式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱通过解析文档为用户提供需要抓取的数据因为简单所以不需要多少代码就可以写出一个完整的应用程序。 BeautifulSoup 自动将输入文档转换为 Unicode 编码输出文档转换为 utf-8 编码。你不需要考虑编码方式除非文档没有指定一个编码方式这时你仅仅需要说明一下原始编码方式就可以了。 BeautifulSoup 已成为和 lxml、html5lib 一样出色的 Python 解释器为用户灵活地提供不同的解析策略或强劲的速度。 所以说利用它可以省去很多烦琐的提取工作提高了解析效率。
2. 准备工作
在开始之前请确保已经正确安装好了 Beautiful Soup 和 lxml如果没有安装可以参考第 1 章的内容。
3. 解析器
Beautiful Soup 在解析时实际上依赖解析器它除了支持 Python 标准库中的 HTML 解析器外还支持一些第三方解析器比如 lxml。列出了 Beautiful Soup 支持的解析器。
Beautiful Soup 支持的解析器
解析器使用方法优势劣势Python 标准库BeautifulSoup(markup, html.parser)Python 的内置标准库、执行速度适中 、文档容错能力强Python 2.7.3 or 3.2.2) 前的版本中文容错能力差LXML HTML 解析器BeautifulSoup(markup, lxml)速度快、文档容错能力强需要安装 C 语言库LXML XML 解析器BeautifulSoup(markup, xml)速度快、唯一支持 XML 的解析器需要安装 C 语言库html5libBeautifulSoup(markup, html5lib)最好的容错性、以浏览器的方式解析文档、生成 HTML5 格式的文档速度慢、不依赖外部扩展
通过以上对比可以看出lxml 解析器有解析 HTML 和 XML 的功能而且速度快容错能力强所以推荐使用它。
如果使用 lxml那么在初始化 Beautiful Soup 时可以把第二个参数改为 lxml 即可
from bs4 import BeautifulSoup
soup BeautifulSoup(pHello/p, lxml)
print(soup.p.string)
在后面Beautiful Soup 的用法实例也统一用这个解析器来演示。
4. 基本使用
下面首先用实例来看看 Beautiful Soup 的基本用法
html
htmlheadtitleThe Dormouses story/title/head
body
p classtitle namedromousebThe Dormouses story/b/p
p classstoryOnce upon a time there were three little sisters; and their names were
a hrefhttp://example.com/elsie classsister idlink1!-- Elsie --/a,
a hrefhttp://example.com/lacie classsister idlink2Lacie/a and
a hrefhttp://example.com/tillie classsister idlink3Tillie/a;
and they lived at the bottom of a well./p
p classstory.../pfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.prettify())
print(soup.title.string)
运行结果
htmlheadtitleThe Dormouses story/title/headbodyp classtitle namedromousebThe Dormouses story/b/pp classstoryOnce upon a time there were three little sisters; and their names werea classsister hrefhttp://example.com/elsie idlink1!-- Elsie --/a,a classsister hrefhttp://example.com/lacie idlink2Lacie/aanda classsister hrefhttp://example.com/tillie idlink3Tillie/a;
and they lived at the bottom of a well./pp classstory.../p/body
/html
The Dormouses story
这里首先声明变量 html它是一个 HTML 字符串。但是需要注意的是它并不是一个完整的 HTML 字符串因为 body 和 html 节点都没有闭合。接着我们将它当作第一个参数传给 BeautifulSoup 对象该对象的第二个参数为解析器的类型这里使用 lxml此时就完成了 BeaufulSoup 对象的初始化。然后将这个对象赋值给 soup 变量。
接下来就可以调用 soup 的各个方法和属性解析这串 HTML 代码了。
首先调用 prettify() 方法。这个方法可以把要解析的字符串以标准的缩进格式输出。这里需要注意的是输出结果里面包含 body 和 html 节点也就是说对于不标准的 HTML 字符串 BeautifulSoup可以自动更正格式。这一步不是由 prettify() 方法做的而是在初始化 BeautifulSoup 时就完成了。
然后调用 soup.title.string这实际上是输出 HTML 中 title 节点的文本内容。所以soup.title 可以选出 HTML 中的 title 节点再调用 string 属性就可以得到里面的文本了所以我们可以通过简单调用几个属性完成文本提取这是不是非常方便
5. 节点选择器
直接调用节点的名称就可以选择节点元素再调用 string 属性就可以得到节点内的文本了这种选择方式速度非常快。如果单个节点结构层次非常清晰可以选用这种方式来解析。
选择元素
下面再用一个例子详细说明选择元素的方法
html
htmlheadtitleThe Dormouses story/title/head
body
p classtitle namedromousebThe Dormouses story/b/p
p classstoryOnce upon a time there were three little sisters; and their names were
a hrefhttp://example.com/elsie classsister idlink1!-- Elsie --/a,
a hrefhttp://example.com/lacie classsister idlink2Lacie/a and
a hrefhttp://example.com/tillie classsister idlink3Tillie/a;
and they lived at the bottom of a well./p
p classstory.../pfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.title)
print(type(soup.title))
print(soup.title.string)
print(soup.head)
print(soup.p)
运行结果
titleThe Dormouses story/title
class bs4.element.Tag
The Dormouses story
headtitleThe Dormouses story/title/head
p classtitle namedromousebThe Dormouses story/b/p
这里依然选用刚才的 HTML 代码首先打印输出 title 节点的选择结果输出结果正是 title 节点加里面的文字内容。接下来输出它的类型是 bs4.element.Tag 类型这是 Beautiful Soup 中一个重要的数据结构。经过选择器选择后选择结果都是这种 Tag 类型。Tag 具有一些属性比如 string 属性调用该属性可以得到节点的文本内容所以接下来的输出结果正是节点的文本内容。
接下来我们又尝试选择了 head 节点结果也是节点加其内部的所有内容。最后选择了 p 节点。不过这次情况比较特殊我们发现结果是第一个 p 节点的内容后面的几个 p 节点并没有选到。也就是说当有多个节点时这种选择方式只会选择到第一个匹配的节点其他的后面节点都会忽略。
提取信息
上面演示了调用 string 属性来获取文本的值那么如何获取节点属性的值呢如何获取节点名呢下面我们来统一梳理一下信息的提取方式。
获取名称
可以利用 name 属性获取节点的名称。这里还是以上面的文本为例选取 title 节点然后调用 name 属性就可以得到节点名称
print(soup.title.name)
运行结果:
title
获取属性
每个节点可能有多个属性比如 id 和 class 等选择这个节点元素后可以调用 attrs 获取所有属性
print(soup.p.attrs)
print(soup.p.attrs[name])
运行结果
{class: [title], name: dromouse}
dromouse
可以看到attrs 的返回结果是字典形式它把选择的节点的所有属性和属性值组合成一个字典。接下来如果要获取 name 属性就相当于从字典中获取某个键值只需要用中括号加属性名就可以了。比如要获取 name 属性就可以通过 attrs[name] 来得到。
其实这样有点烦琐还有一种更简单的获取方式可以不用写 attrs直接在节点元素后面加中括号传入属性名就可以获取属性值了。样例如下
print(soup.p[name])
print(soup.p[class])
运行结果如下
dromouse
[title]
这里需要注意的是有的返回结果是字符串有的返回结果是字符串组成的列表。比如name 属性的值是唯一的返回的结果就是单个字符串。而对于 class一个节点元素可能有多个 class所以返回的是列表。在实际处理过程中我们要注意判断类型。
获取内容
可以利用 string 属性获取节点元素包含的文本内容比如要获取第一个 p 节点的文本
print(soup.p.string)
运行结果如下
The Dormouses story
再次注意一下这里选择到的 p 节点是第一个 p 节点获取的文本也是第一个 p 节点里面的文本。
嵌套选择
在上面的例子中我们知道每一个返回结果都是 bs4.element.Tag 类型它同样可以继续调用节点进行下一步的选择。比如我们获取了 head 节点元素我们可以继续调用 head 来选取其内部的 head 节点元素
html
htmlheadtitleThe Dormouses story/title/head
bodyfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.head.title)
print(type(soup.head.title))
print(soup.head.title.string)
运行结果如下
titleThe Dormouses story/title
class bs4.element.Tag
The Dormouses story
第一行结果是调用 head 之后再次调用 title 而选择的 title 节点元素。然后打印输出了它的类型可以看到它仍然是 bs4.element.Tag 类型。也就是说我们在 Tag 类型的基础上再次选择得到的依然还是 Tag 类型每次返回的结果都相同所以这样就可以做嵌套选择了。
最后输出它的 string 属性也就是节点里的文本内容。
关联选择
在做选择的时候有时候不能做到一步就选到想要的节点元素需要先选中某一个节点元素然后以它为基准再选择它的子节点、父节点、兄弟节点等这里就来介绍如何选择这些节点元素。
子节点和子孙节点
选取节点元素之后如果想要获取它的直接子节点可以调用 contents 属性示例如下
html
htmlheadtitleThe Dormouses story/title/headbodyp classstoryOnce upon a time there were three little sisters; and their names werea hrefhttp://example.com/elsie classsister idlink1spanElsie/span/aa hrefhttp://example.com/lacie classsister idlink2Lacie/a anda hrefhttp://example.com/tillie classsister idlink3Tillie/aand they lived at the bottom of a well./pp classstory.../pfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.p.contents)
运行结果如下
[\n Once upon a time there were three little sisters; and their names were\n , a classsister hrefhttp://example.com/elsie idlink1
spanElsie/span
/a, \n, a classsister hrefhttp://example.com/lacie idlink2Lacie/a, \n and\n , a classsister hrefhttp://example.com/tillie idlink3Tillie/a, \n and they lived at the bottom of a well.\n ]
可以看到返回结果是列表形式。p 节点里既包含文本又包含节点最后会将它们以列表形式统一返回。
需要注意的是列表中的每个元素都是 p 节点的直接子节点。比如第一个 a 节点里面包含一层 span 节点这相当于孙子节点了但是返回结果并没有单独把 span 节点选出来。所以说contents 属性得到的结果是直接子节点的列表。
同样我们可以调用 children 属性得到相应的结果
from bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.p.children)
for i, child in enumerate(soup.p.children):print(i, child)
运行结果如下
list_iterator object at 0x1064f7dd8
0 Once upon a time there were three little sisters; and their names were1 a classsister hrefhttp://example.com/elsie idlink1
spanElsie/span
/a
2 3 a classsister hrefhttp://example.com/lacie idlink2Lacie/a
4 and5 a classsister hrefhttp://example.com/tillie idlink3Tillie/a
6 and they lived at the bottom of a well.
还是同样的 HTML 文本这里调用了 children 属性来选择返回结果是生成器类型。接下来我们用 for 循环输出相应的内容。
如果要得到所有的子孙节点的话可以调用 descendants 属性
from bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.p.descendants)
for i, child in enumerate(soup.p.descendants):print(i, child)
运行结果如下
generator object descendants at 0x10650e678
0 Once upon a time there were three little sisters; and their names were1 a classsister hrefhttp://example.com/elsie idlink1
spanElsie/span
/a
2 3 spanElsie/span
4 Elsie
5 6 7 a classsister hrefhttp://example.com/lacie idlink2Lacie/a
8 Lacie
9 and10 a classsister hrefhttp://example.com/tillie idlink3Tillie/a
11 Tillie
12 and they lived at the bottom of a well.
此时返回结果还是生成器。遍历输出一下可以看到这次的输出结果就包含了 span 节点。descendants 会递归查询所有子节点得到所有的子孙节点。
父节点和祖先节点
如果要获取某个节点元素的父节点可以调用 parent 属性
html
htmlheadtitleThe Dormouses story/title/headbodyp classstoryOnce upon a time there were three little sisters; and their names werea hrefhttp://example.com/elsie classsister idlink1spanElsie/span/a/pp classstory.../pfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.a.parent)
运行结果如下
p classstoryOnce upon a time there were three little sisters; and their names werea classsister hrefhttp://example.com/elsie idlink1
spanElsie/span
/a
/p
这里我们选择的是第一个 a 节点的父节点元素。很明显它的父节点是 p 节点输出结果便是 p 节点及其内部的内容。
需要注意的是这里输出的仅仅是 a 节点的直接父节点而没有再向外寻找父节点的祖先节点。如果想获取所有的祖先节点可以调用 parents 属性
html
htmlbodyp classstorya hrefhttp://example.com/elsie classsister idlink1spanElsie/span/a/pfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(type(soup.a.parents))
print(list(enumerate(soup.a.parents)))
运行结果如下
class generator
[(0, p classstory
a classsister hrefhttp://example.com/elsie idlink1
spanElsie/span
/a
/p), (1, body
p classstory
a classsister hrefhttp://example.com/elsie idlink1
spanElsie/span
/a
/p
/body), (2, html
body
p classstory
a classsister hrefhttp://example.com/elsie idlink1
spanElsie/span
/a
/p
/body/html), (3, html
body
p classstory
a classsister hrefhttp://example.com/elsie idlink1
spanElsie/span
/a
/p
/body/html)]
可以发现返回结果是生成器类型。这里用列表输出了它的索引和内容而列表中的元素就是 a 节点的祖先节点。
兄弟节点
上面说明了子节点和父节点的获取方式如果要获取同级的节点也就是兄弟节点应该怎么办呢示例如下
html
htmlbodyp classstoryOnce upon a time there were three little sisters; and their names werea hrefhttp://example.com/elsie classsister idlink1spanElsie/span/aHelloa hrefhttp://example.com/lacie classsister idlink2Lacie/a anda hrefhttp://example.com/tillie classsister idlink3Tillie/aand they lived at the bottom of a well./pfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(Next Sibling, soup.a.next_sibling)
print(Prev Sibling, soup.a.previous_sibling)
print(Next Siblings, list(enumerate(soup.a.next_siblings)))
print(Prev Siblings, list(enumerate(soup.a.previous_siblings)))
运行结果如下
Next Sibling HelloPrev Sibling Once upon a time there were three little sisters; and their names wereNext Siblings [(0, \n Hello\n ), (1, a classsister hrefhttp://example.com/lacie idlink2Lacie/a), (2, \n and\n ), (3, a classsister hrefhttp://example.com/tillie idlink3Tillie/a), (4, \n and they lived at the bottom of a well.\n )]
Prev Siblings [(0, \n Once upon a time there were three little sisters; and their names were\n )]
可以看到这里调用了 4 个属性其中 next_sibling 和 previous_sibling 分别获取节点的下一个和上一个兄弟元素next_siblings 和 previous_siblings 则分别返回后面和前面的兄弟节点。
提取信息
前面讲解了关联元素节点的选择方法如果想要获取它们的一些信息比如文本、属性等也用同样的方法示例如下
html
htmlbodyp classstoryOnce upon a time there were three little sisters; and their names werea hrefhttp://example.com/elsie classsister idlink1Bob/aa hrefhttp://example.com/lacie classsister idlink2Lacie/a /pfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(Next Sibling:)
print(type(soup.a.next_sibling))
print(soup.a.next_sibling)
print(soup.a.next_sibling.string)
print(Parent:)
print(type(soup.a.parents))
print(list(soup.a.parents)[0])
print(list(soup.a.parents)[0].attrs[class])
运行结果
Next Sibling:
class bs4.element.Tag
a classsister hrefhttp://example.com/lacie idlink2Lacie/a
Lacie
Parent:
class generator
p classstoryOnce upon a time there were three little sisters; and their names werea classsister hrefhttp://example.com/elsie idlink1Bob/aa classsister hrefhttp://example.com/lacie idlink2Lacie/a
/p
[story]
如果返回结果是单个节点那么可以直接调用 string、attrs 等属性获得其文本和属性如果返回结果是多个节点的生成器则可以转为列表后取出某个元素然后再调用 string、attrs 等属性获取其对应节点的文本和属性。
6. 方法选择器
前面所讲的选择方法都是通过属性来选择的这种方法非常快但是如果进行比较复杂的选择的话它就比较烦琐不够灵活了。幸好Beautiful Soup 还为我们提供了一些查询方法比如 find_all 和 find 等调用它们然后传入相应的参数就可以灵活查询了。
find_all
find_all顾名思义就是查询所有符合条件的元素可以给它传入一些属性或文本来得到符合条件的元素功能十分强大。
它的 API 如下
find_all(name , attrs , recursive , text , **kwargs)
name
我们可以根据节点名来查询元素下面我们用一个实例来感受一下
html
div classpaneldiv classpanel-headingh4Hello/h4/divdiv classpanel-bodyul classlist idlist-1li classelementFoo/lili classelementBar/lili classelementJay/li/ulul classlist list-small idlist-2li classelementFoo/lili classelementBar/li/ul/div
/divfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.find_all(nameul))
print(type(soup.find_all(nameul)[0]))
运行结果
[ul classlist idlist-1
li classelementFoo/li
li classelementBar/li
li classelementJay/li
/ul, ul classlist list-small idlist-2
li classelementFoo/li
li classelementBar/li
/ul]
class bs4.element.Tag
这里我们调用了 find_all 方法传入 name 参数其参数值为 ul。也就是说我们想要查询所有 ul 节点返回结果是列表类型长度为 2每个元素依然都是 bs4.element.Tag 类型。
因为都是 Tag 类型所以依然可以进行嵌套查询。还是同样的文本这里查询出所有 ul 节点后再继续查询其内部的 li 节点
for ul in soup.find_all(nameul):print(ul.find_all(nameli))
运行结果如下
[li classelementFoo/li, li classelementBar/li, li classelementJay/li]
[li classelementFoo/li, li classelementBar/li]
返回结果是列表类型列表中的每个元素依然还是 Tag 类型。
接下来我们就可以遍历每个 li 获取它的文本了。
for ul in soup.find_all(nameul):print(ul.find_all(nameli))for li in ul.find_all(nameli):print(li.string)
运行结果如下
[li classelementFoo/li, li classelementBar/li, li classelementJay/li]
Foo
Bar
Jay
[li classelementFoo/li, li classelementBar/li]
Foo
Bar
attrs
除了根据节点名查询我们也可以传入一些属性来进行查询我们用一个实例感受一下
html
div classpaneldiv classpanel-headingh4Hello/h4/divdiv classpanel-bodyul classlist idlist-1 nameelementsli classelementFoo/lili classelementBar/lili classelementJay/li/ulul classlist list-small idlist-2li classelementFoo/lili classelementBar/li/ul/div
/divfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.find_all(attrs{id: list-1}))
print(soup.find_all(attrs{name: elements}))
运行结果
[ul classlist idlist-1 nameelements
li classelementFoo/li
li classelementBar/li
li classelementJay/li
/ul]
[ul classlist idlist-1 nameelements
li classelementFoo/li
li classelementBar/li
li classelementJay/li
/ul]
这里查询的时候传入的是 attrs 参数参数的类型是字典类型。比如要查询 id 为 list-1 的节点可以传入 attrs{id: list-1} 的查询条件得到的结果是列表形式包含的内容就是符合 id 为 list-1 的所有节点。在上面的例子中符合条件的元素个数是 1所以结果是长度为 1 的列表。
对于一些常用的属性比如 id 和 class 等我们可以不用 attrs 来传递。比如要查询 id 为 list-1 的节点可以直接传入 id 这个参数。还是上面的文本我们换一种方式来查询
from bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.find_all(idlist-1))
print(soup.find_all(class_element))
运行结果如下
[ul classlist idlist-1
li classelementFoo/li
li classelementBar/li
li classelementJay/li
/ul]
[li classelementFoo/li, li classelementBar/li, li classelementJay/li, li classelementFoo/li, li classelementBar/li]
这里直接传入 idlist-1就可以查询 id 为 list-1 的节点元素了。而对于 class 来说由于 class 在 Python 里是一个关键字所以后面需要加一个下划线即 class_element返回的结果依然还是 Tag 组成的列表。
text
text 参数可用来匹配节点的文本传入的形式可以是字符串可以是正则表达式对象示例如下
import re
html
div classpaneldiv classpanel-bodyaHello, this is a link/aaHello, this is a link, too/a/div
/divfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.find_all(textre.compile(link)))
运行结果
[Hello, this is a link, Hello, this is a link, too]
这里有两个 a 节点其内部包含文本信息。这里在 find_all() 方法中传入 text 参数该参数为正则表达式对象结果返回所有匹配正则表达式的节点文本组成的列表。
find
除了 find_all 方法还有 find 方法只不过 find 方法返回的是单个元素也就是第一个匹配的元素而 find_all 返回的是所有匹配的元素组成的列表。示例如下
html
div classpaneldiv classpanel-headingh4Hello/h4/divdiv classpanel-bodyul classlist idlist-1li classelementFoo/lili classelementBar/lili classelementJay/li/ulul classlist list-small idlist-2li classelementFoo/lili classelementBar/li/ul/div
/divfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.find(nameul))
print(type(soup.find(nameul)))
print(soup.find(class_list))
运行结果
ul classlist idlist-1
li classelementFoo/li
li classelementBar/li
li classelementJay/li
/ul
class bs4.element.Tag
ul classlist idlist-1
li classelementFoo/li
li classelementBar/li
li classelementJay/li
/ul
返回结果不再是列表形式而是第一个匹配的节点元素类型依然是 Tag 类型。
另外还有许多的查询方法用法与前面介绍的 find_all、find 方法完全相同只不过查询范围不同在此做一下简单的说明。
find_parents 和 find_parent前者返回所有祖先节点后者返回直接父节点。
find_next_siblings 和 find_next_sibling前者返回后面所有的兄弟节点后者返回后面第一个兄弟节点。
find_previous_siblings 和 find_previous_sibling前者返回前面所有的兄弟节点后者返回前面第一个兄弟节点。
find_all_next 和 find_next前者返回节点后所有符合条件的节点后者返回第一个符合条件的节点。
find_all_previous 和 find_previous前者返回节点前所有符合条件的节点后者返回第一个符合条件的节点。
7. CSS 选择器
Beautiful Soup 还提供了另外一种选择器那就是 CSS 选择器。如果对 Web 开发熟悉的话那么对 CSS 选择器肯定也不陌生。如果不熟悉的话可以参考 CSS 选择器参考手册 了解。
使用 CSS 选择器只需要调用 select 方法传入相应的 CSS 选择器即可我们用一个实例来感受一下
html
div classpaneldiv classpanel-headingh4Hello/h4/divdiv classpanel-bodyul classlist idlist-1li classelementFoo/lili classelementBar/lili classelementJay/li/ulul classlist list-small idlist-2li classelementFoo/lili classelementBar/li/ul/div
/divfrom bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
print(soup.select(.panel .panel-heading))
print(soup.select(ul li))
print(soup.select(#list-2 .element))
print(type(soup.select(ul)[0]))
运行结果如下
[div classpanel-heading
h4Hello/h4
/div]
[li classelementFoo/li, li classelementBar/li, li classelementJay/li, li classelementFoo/li, li classelementBar/li]
[li classelementFoo/li, li classelementBar/li]
class bs4.element.Tag
这里我们用了 3 次 CSS 选择器返回的结果均是符合 CSS 选择器的节点组成的列表。例如select(ul li) 则是选择所有 ul 节点下面的所有 li 节点结果便是所有的 li 节点组成的列表。
最后一句我们打印输出了列表中元素的类型可以看到类型依然是 Tag 类型。
嵌套选择
select 方法同样支持嵌套选择例如我们先选择所有 ul 节点再遍历每个 ul 节点选择其 li 节点样例如下
from bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
for ul in soup.select(ul):print(ul.select(li))
运行结果如下
[li classelementFoo/li, li classelementBar/li, li classelementJay/li]
[li classelementFoo/li, li classelementBar/li]
可以看到正常输出了遍历每个 ul 节点之后其下的所有 li 节点组成的列表。
获取属性
我们知道节点类型是 Tag 类型所以获取属性还可以用原来的方法。仍然是上面的 HTML 文本这里尝试获取每个 ul 节点的 id 属性
from bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
for ul in soup.select(ul):print(ul[id])print(ul.attrs[id])
运行结果如下
list-1
list-1
list-2
list-2
可以看到直接传入中括号和属性名和通过 attrs 属性获取属性值都是可以成功的。
获取文本
要获取文本当然也可以用前面所讲的 string 属性。此外还有一个方法那就是 get_text示例如下
from bs4 import BeautifulSoup
soup BeautifulSoup(html, lxml)
for li in soup.select(li):print(Get Text:, li.get_text())print(String:, li.string)
运行结果
Get Text: Foo
String: Foo
Get Text: Bar
String: Bar
Get Text: Jay
String: Jay
Get Text: Foo
String: Foo
Get Text: Bar
String: Bar
二者的效果是完全一致的都可以获取到节点的文本值。
8. 结语
到此 BeautifulSoup 的使用介绍基本就结束了最后做一下简单的总结 推荐使用 LXML 解析库必要时使用 html.parser。 节点选择筛选功能弱但是速度快。 建议使用 find、find_all 方法查询匹配单个结果或者多个结果。 如果对 CSS 选择器熟悉的话可以使用 select 选择法。 如果本文对你有帮助不要忘记点赞收藏关注 文章转载自: http://www.morning.rwpfb.cn.gov.cn.rwpfb.cn http://www.morning.dqwykj.com.gov.cn.dqwykj.com http://www.morning.rbsxf.cn.gov.cn.rbsxf.cn http://www.morning.mrkbz.cn.gov.cn.mrkbz.cn http://www.morning.xcnwf.cn.gov.cn.xcnwf.cn http://www.morning.cknsx.cn.gov.cn.cknsx.cn http://www.morning.kjfsd.cn.gov.cn.kjfsd.cn http://www.morning.kfysh.com.gov.cn.kfysh.com http://www.morning.bwdnx.cn.gov.cn.bwdnx.cn http://www.morning.rzmsl.cn.gov.cn.rzmsl.cn http://www.morning.lrprj.cn.gov.cn.lrprj.cn http://www.morning.ppqzb.cn.gov.cn.ppqzb.cn http://www.morning.swkzk.cn.gov.cn.swkzk.cn http://www.morning.btns.cn.gov.cn.btns.cn http://www.morning.bdqpl.cn.gov.cn.bdqpl.cn http://www.morning.syhwc.cn.gov.cn.syhwc.cn http://www.morning.hkysq.cn.gov.cn.hkysq.cn http://www.morning.fdrwk.cn.gov.cn.fdrwk.cn http://www.morning.fnpyk.cn.gov.cn.fnpyk.cn http://www.morning.hjjkz.cn.gov.cn.hjjkz.cn http://www.morning.zhmgcreativeeducation.cn.gov.cn.zhmgcreativeeducation.cn http://www.morning.nmpdm.cn.gov.cn.nmpdm.cn http://www.morning.lrzst.cn.gov.cn.lrzst.cn http://www.morning.wwgpy.cn.gov.cn.wwgpy.cn http://www.morning.rszbj.cn.gov.cn.rszbj.cn http://www.morning.jkcpl.cn.gov.cn.jkcpl.cn http://www.morning.dfdhx.cn.gov.cn.dfdhx.cn http://www.morning.tdcql.cn.gov.cn.tdcql.cn http://www.morning.nkiqixr.cn.gov.cn.nkiqixr.cn http://www.morning.huihuangwh.cn.gov.cn.huihuangwh.cn http://www.morning.bwkhp.cn.gov.cn.bwkhp.cn http://www.morning.uqrphxm.cn.gov.cn.uqrphxm.cn http://www.morning.fwdln.cn.gov.cn.fwdln.cn http://www.morning.rrcxs.cn.gov.cn.rrcxs.cn http://www.morning.nrxsl.cn.gov.cn.nrxsl.cn http://www.morning.qysnd.cn.gov.cn.qysnd.cn http://www.morning.wyrkp.cn.gov.cn.wyrkp.cn http://www.morning.qcztm.cn.gov.cn.qcztm.cn http://www.morning.ykmtz.cn.gov.cn.ykmtz.cn http://www.morning.bsbcp.cn.gov.cn.bsbcp.cn http://www.morning.myhpj.cn.gov.cn.myhpj.cn http://www.morning.qcwrm.cn.gov.cn.qcwrm.cn http://www.morning.qxdrw.cn.gov.cn.qxdrw.cn http://www.morning.rjnrf.cn.gov.cn.rjnrf.cn http://www.morning.rxfbf.cn.gov.cn.rxfbf.cn http://www.morning.kxqpm.cn.gov.cn.kxqpm.cn http://www.morning.fbtgp.cn.gov.cn.fbtgp.cn http://www.morning.gqjwz.cn.gov.cn.gqjwz.cn http://www.morning.jxgyg.cn.gov.cn.jxgyg.cn http://www.morning.nkpls.cn.gov.cn.nkpls.cn http://www.morning.ctsjq.cn.gov.cn.ctsjq.cn http://www.morning.rqfzp.cn.gov.cn.rqfzp.cn http://www.morning.yhpq.cn.gov.cn.yhpq.cn http://www.morning.khlxd.cn.gov.cn.khlxd.cn http://www.morning.lhrcr.cn.gov.cn.lhrcr.cn http://www.morning.dmjhp.cn.gov.cn.dmjhp.cn http://www.morning.yjfzk.cn.gov.cn.yjfzk.cn http://www.morning.rpjyl.cn.gov.cn.rpjyl.cn http://www.morning.mlwhd.cn.gov.cn.mlwhd.cn http://www.morning.xdhcr.cn.gov.cn.xdhcr.cn http://www.morning.lhldx.cn.gov.cn.lhldx.cn http://www.morning.qqxmj.cn.gov.cn.qqxmj.cn http://www.morning.lpmdy.cn.gov.cn.lpmdy.cn http://www.morning.nfbkp.cn.gov.cn.nfbkp.cn http://www.morning.gczqt.cn.gov.cn.gczqt.cn http://www.morning.ryrpq.cn.gov.cn.ryrpq.cn http://www.morning.ynlbj.cn.gov.cn.ynlbj.cn http://www.morning.hdlhh.cn.gov.cn.hdlhh.cn http://www.morning.llcgz.cn.gov.cn.llcgz.cn http://www.morning.rqxmz.cn.gov.cn.rqxmz.cn http://www.morning.fkwgk.cn.gov.cn.fkwgk.cn http://www.morning.gstmn.cn.gov.cn.gstmn.cn http://www.morning.qjrjs.cn.gov.cn.qjrjs.cn http://www.morning.wnkqt.cn.gov.cn.wnkqt.cn http://www.morning.pwqyd.cn.gov.cn.pwqyd.cn http://www.morning.ltfnl.cn.gov.cn.ltfnl.cn http://www.morning.kjgdm.cn.gov.cn.kjgdm.cn http://www.morning.mhybs.cn.gov.cn.mhybs.cn http://www.morning.mjxgs.cn.gov.cn.mjxgs.cn http://www.morning.lgnrl.cn.gov.cn.lgnrl.cn