python学习笔记(BeautifulSoup4)
BeautifulSoup4是一个从html或者xml中提取数据的py库。
lxml是局部遍历,BS是基于HTML DOM的,会载入整个文档,解析整个DOM树,时间和空间都会大很多。
#创建BS对象
soup = BeautifulSoup(html)
#格式化打印出整个soup对象的内容
print (soup.prettify())
1.Tag 就是html中的一个个标签
tag有两个重要的属性,name和attrs
2.NavigableString 就是指内容
#打印出标签p中的内容
print (soup.p.string)
3.BeautifulSoup
表示的是一个文档的内容
⼤部分时候,可以把它当作Tag 对象, 是⼀个特殊的 Tag
4.Comment
特殊的NavigableString对象
输出的内容不包括注释符号
遍历文档树:
1.直接子节点:.content和.children属性
.content
tag 的 .content 属性可以将tag的⼦节点以列表的⽅式输出
print (soup.head.contents)
#[<title>The Dormouse's story</title>]
输出⽅式为列表, 我们可以⽤列表索引来获取它的某⼀个元素
print (soup.head.contents[0])
#<title>The Dormouse's story</title>
.children
它返回的是⼀个 list ⽣成器对象
print (soup.head.children)
#<listiterator object at 0x7f71457f5710>
for
child in
soup.body.children:
print (child)
2.所有子孙节点:.descendants属性
contents 和 .children 属性仅包含tag的直接⼦节点, .descendants 属性可以对所有tag的⼦孙节点进⾏递归循环, 和 children类似, 我们也需要遍历获取其中的内容。
for
child in
soup.descendants:
print (child)
3.节点内容:.string属性
如果tag只有⼀个 NavigableString 类型⼦节点,那么这个tag可以使⽤ .string得到⼦节点。 如果⼀个tag仅有⼀个⼦节点,那么这个tag也可以使⽤ .string ⽅法,输出结果与当前唯⼀⼦节点的
.string 结果相同。
通俗点说就是: 如果⼀个标签⾥⾯没有标签了, 那么 .string 就会返回标签⾥⾯的内容。 如果标签⾥⾯只有唯⼀的⼀个标签了, 那么 .string 也会返回最⾥⾯的内容。
搜索⽂档树
1. find_all(name, attrs, recursive, text,**kwargs)
1)
name 参数
name 参数可以查找所有名字为 name 的tag,字符串对象会被⾃动忽略掉
A.传字符串
最简单的过滤器是字符串.在搜索⽅法中传⼊⼀个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下⾯的例⼦⽤于查找⽂档中所有的 <b> 标签:
soup.find_all('b')
# [<b>The Dormouse's story</b>]
B.传正则表达式
如果传⼊正则表达式作为参数,Beautiful Soup会通过正则表达式的 match()来匹配内容.下⾯例⼦中找出所有以b开头的标签,这表示 <body> 和 <b> 标签都应该被找到
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
# body
# b
C.传列表
如果传⼊列表参数,Beautiful Soup会将与列表中任⼀元素匹配的内容返回.下⾯代码找到⽂档中所有 <a> 标签和 <b> 标签:
soup.find_all(["a",
"b"])
# [<b>The Dormouse's story</b>,
# <a class="sister" href="http://example.com/elsie"; id="link1">Els
ie</a>,
# <a class="sister" href="http://example.com/lacie"; id="link2">Lac
ie</a>,
# <a class="sister" href="http://example.com/tillie"; id="link3">Ti
llie</a>]
2) keyword 参数
soup.find_all(id='link2')
ie</a>]
3) text 参数
通过 text 参数可以搜搜⽂档中的字符串内容, 与 name 参数的可选值⼀样,text 参数接受 字符串 , 正则表达式 , 列表
soup.find_all(text="Elsie")
# [u'Elsie']
CSS选择器
这就是另⼀种与 find_all ⽅法有异曲同⼯之妙的查找⽅法.
- 写 CSS 时, 标签名不加任何修饰, 类名前加 . , id名前加 #
- 在这⾥我们也可以利⽤类似的⽅法来筛选元素, ⽤到的⽅法是soup.select() , 返回类型是 list
( 1) 通过标签名查找
(6) 获取内容