门户移动网站建设,企业建设网站的价值,网页设计与网站建设过程,能不能不用虚拟主机建设网站简单来说#xff0c;BeautifulSoup 就是 Python 的一个 HTML 或 XML 的解析库#xff0c;我们可以用它来方便地从网页中提取数据#xff0c;官方的解释如下#xff1a;
BeautifulSoup 提供一些简单的、Python 式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具…简单来说BeautifulSoup 就是 Python 的一个 HTML 或 XML 的解析库我们可以用它来方便地从网页中提取数据官方的解释如下
BeautifulSoup 提供一些简单的、Python 式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱通过解析文档为用户提供需要抓取的数据因为简单所以不需要多少代码就可以写出一个完整的应用程序。 BeautifulSoup 自动将输入文档转换为 Unicode 编码输出文档转换为 utf-8 编码。你不需要考虑编码方式除非文档没有指定一个编码方式这时你仅仅需要说明一下原始编码方式就可以了。 BeautifulSoup 已成为和 lxml、html5lib 一样出色的 Python 解释器为用户灵活地提供不同的解析策略或强劲的速度。
解析器
Beautiful Soup 在解析时实际上依赖解析器它除了支持 Python 标准库中的 HTML 解析器外还支持一些第三方解析器比如 lxml。
解析器使用方法优势劣势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那么在初始化 Beautiful Soup 时可以把第二个参数改为 lxml 即可
from bs4 import BeautifulSoup
soup BeautifulSoup(pHello/p, lxml)
print(soup.p.string)基本使用
用实例来看看 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运行结果
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结果如下
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
/htmlThe Dormouses story运行结果
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 变量。
调用 prettify() 方法。这个方法可以把要解析的字符串以标准的缩进格式输出。这里需要注意的是输出结果里面包含 body 和 html 节点也就是说对于不标准的 HTML 字符串 BeautifulSoup可以自动更正格式。这一步不是由 prettify() 方法做的而是在初始化 BeautifulSoup 时就完成了。
调用 soup.title.string这实际上是输出 HTML 中 title 节点的文本内容。所以soup.title 可以选出 HTML 中的 title 节点再调用 string 属性就可以得到里面的文本了。可以通过简单调用几个属性完成文本提取比起XPath更加方便。
节点选择器
选择元素
依然选用刚才的 HTML 代码
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首先打印输出 title 节点的选择结果输出结果正是 title 节点加里面的文字内容。接下来输出它的类型是 bs4.element.Tag 类型这是 Beautiful Soup 中一个重要的数据结构。经过选择器选择后选择结果都是这种 Tag 类型。Tag 具有一些属性比如 string 属性调用该属性可以得到节点的文本内容所以接下来的输出结果正是节点的文本内容。
接着尝试选择了 head 节点结果也是节点加其内部的所有内容。最后选择了 p 节点。不过这次情况比较特殊我们发现结果是第一个 p 节点的内容后面的几个 p 节点并没有选到。也就是说当有多个节点时这种选择方式只会选择到第一个匹配的节点其他的后面节点都会忽略。
提取信息
获取名称
可以利用 name 属性获取节点的名称。这里还是以上面的文本为例选取 title 节点然后调用 name 属性就可以得到节点名称
print(soup.title.name)获取属性
每个节点可能有多个属性比如 id 和 class 等选择这个节点元素后可以调用 attrs 获取所有属性
print(soup.p.attrs)
print(soup.p.attrs[name])运行结果
{class: [title], name: dromouse}
dromouseattrs 的返回结果是字典形式它把选择的节点的所有属性和属性值组合成一个字典。接下来如果要获取 name 属性就相当于从字典中获取某个键值只需要用中括号加属性名就可以了。
还有一种更简单的获取方式可以不用写 attrs直接在节点元素后面加中括号传入属性名就可以获取属性值了。
print(soup.p[name])
print(soup.p[class])获取内容
利用 string 属性获取节点元素包含的文本内容。
嵌套选择
在上面的例子中我们知道每一个返回结果都是 bs4.element.Tag 类型它同样可以继续调用节点进行下一步的选择。比如我们获取了 head 节点元素我们可以继续调用 head 来选取其内部的 head 节点元素
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 类型每次返回的结果都相同所以这样就可以做嵌套选择了。
关联选择
有时候不能做到一步就选到想要的节点元素需要先选中某一个节点元素然后以它为基准再选择它的子节点、父节点、兄弟节点等。
子节点和子孙节点
选取节点元素之后如果想要获取它的直接子节点可以调用 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 属性得到相应的结果
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.要得到所有的子孙节点的话可以调用 descendants 属性
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输出结果便是 p 节点及其内部的内容。
如果想获取所有的祖先节点可以调用 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)))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)]兄弟节点
如果要获取同级的节点也就是兄弟节点
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 )]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 等属性获取其对应节点的文本和属性。
方法选择器
Beautiful Soup 还为我们提供了一些查询方法比如 find_all 和 find 等调用它们然后传入相应的参数就可以灵活查询了。
find_all
find_all查询所有符合条件的元素可以给它传入一些属性或文本来得到符合条件的元素.
find_all(name , attrs , recursive , text , **kwargs)find
除了 find_all 方法还有 find 方法只不过 find 方法返回的是单个元素也就是第一个匹配的元素而 find_all 返回的是所有匹配的元素组成的列表。
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前者返回节点前所有符合条件的节点后者返回第一个符合条件的节点。
CSS选择器
使用 CSS 选择器只需要调用 select 方法传入相应的 CSS 选择器即可。
print(soup.select(.panel .panel-heading))
print(soup.select(ul li))
print(soup.select(#list-2 .element))
print(type(soup.select(ul)[0]))select(‘ul li’) 则是选择所有 ul 节点下面的所有 li 节点结果便是所有的 li 节点组成的列表。
嵌套选择
select 方法同样支持嵌套选择例如我们先选择所有 ul 节点再遍历每个 ul 节点选择其 li 节点。
for ul in soup.select(ul):print(ul.select(li))获取属性
节点类型是 Tag 类型所以获取属性还可以用原来的方法。
for ul in soup.select(ul):print(ul[id])print(ul.attrs[id])获取文本
可以用前面所讲的 string 属性。还有一个方法那就是 get_text。
for li in soup.select(li):print(Get Text:, li.get_text())print(String:, li.string)