BeautifuSoup用法整理
摘自: https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#find-all
先来一段html代码
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p>
使用BeautifulSoup获得一个对象
from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc, features="html.parser") print("soup.prettity()")
得到的结果能按照标准的缩进结构输出
四大对象种类
BeautifulSoup将复杂的HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,搜友对象可以归纳4中
1, Tag
2,NavigableString
3,BeautifulSoup
4,Comment
(1): Tag
通俗讲就是HTMl中的一个标签
<title>The Dormouse's story</title>
print(soup.title) # <title>The Dormouse's story</title>
print(soup.head) # <head><title>The Dormouse's story</title></head>
print(soup.p) # <p class="title"><b>The Dormouse's story</b></p>
print(soup.a) # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
验证这些对象的类型
print(type(soup.a)) # <class 'bs4.element.Tag'>
对于Tag,他有两个重要的属性,是name和attts
name
print(soup.name) print(soup.head.name) # [document] # head
soup对象本身比较特殊,他的name即为[document],对于其他内部标签,输出的值便为标签本身的名称
attrs
print(soup.p.attrs) # {'class': ['title']}
把p标签的所有属性打印出来,得到的类型是一个字典
我们想要获取某个属性,可以这样,例如.获取他的class叫什么
print(soup.p["class"]) # ['title']
或者.也可以利用get方法
print(soup.p.get("class"))
我们可以对这些属性和内容等等进行修改
soup.p["class"] = "newClass" print(soup.p) # <p class="newClass"><b>The Dormouse's story</b></p>
不过,对于修改删除的操作,不是我们的主要途径
(2): VavigableString
既然我们已经得到了标签的内容,那么问题来了,我们想获取是标签内部的文字怎么办呢?用.string即可
print(soup.p.string) # The Dormouse's story
来查看一下他的类型
print(type(soup.p.string)) # <class 'bs4.element.NavigableString'>
(3): BeautifulSoup
BeautifulSoup对象表示的是一个文档的全部内容.大部分时候也,可以把他当作Tag对象,是一个特殊的Tag,我们可以分别获取它的类型,名称,以及属性来感受一下
print(type(soup.name)) print(soup.name) print(soup.attrs) # <class 'str'> # [document] # {}
(4): Comment
Comment对象是一个特殊类型的NavigableString对象,其实输出的内容任然不过包括注释符号,但是如果不好好处理他,可能会对我们的文本处理造成意想不到得分麻烦
print(soup.a) print(soup.a.string) print(type(soup.a.string))
运行结果如下
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> Elsie <class 'bs4.element.NavigableString'>
a标签里的内容实际上是注释,但是我们如果利用.string来输出他的内容,我们发现他已经把注释号去掉了,所以这可能会给我们带来不必要的麻烦
另外我们打印输出下他的类型,发现,他是一个Comment类型,所以,我们在使用前最好判断,判断代码如下:
if type(soup.a.string) == bs4.element.NavigableString: print(soup.a.string)
遍历文档树
(1): 直接子节点
要点.contents .children 属性
.contents
print(soup.head.contents) # [<title>The Dormouse's story</title>]
输出方式为列表,我们可以用列表索引来索取它的一个元素
print(soup.head.contents[0]) # <title>The Dormouse's story</title>
.children
它返回的不是一个list,不过我们可以通过白能力获取所有子节点
我们打印输出.children看一下,可以发现他是一个list生成器对象
print(soup.head.children) # <list_iterator object at 0x000001B58241D198>
遍历获取结果
for child in soup.body.children: print(child)
(2): 所有子孙节点
知识点: .descendants 属性
.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也会返回最里面的内容.例如
print(soup.head.string) print(soup.title.string) # The Dormouse's story # The Dormouse's story
如果tag包含了多个子节点,tag就无法确定, .string方法应该调用哪个子节点的内容, .string的输出结果是None
print(soup.html.string) # None
(4) 多个内容
知识点: .string .stripped_strings属性
.strings
for string in soup.strings: print(repr(string))
# u"The Dormouse's story"
.strpped_strings
输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings可以去除多余空白内容
for i in soup.stripped_strings: print(repr(i)) # "The Dormouse's story" # "The Dormouse's story" # 'Once upon a time there were three little sisters; and their names were' # 'Elsie' # ',' # 'Lacie' # 'and' # 'Tillie' # ';\nand they lived at the bottom of a well.' # '...'
(5) 父节点
知识点: .parent 属性
p = soup.p print(p.parent.name) # body
(6): 全部父节点
知识点: .parents 属性
通过元素的 .parents属性可以递归得到元素的所有父节点,例如
content = soup.head.title.string for parent in content.parents: print(parent.name)
(7): 兄节点
知识点: .next_sibling .previous_sibling 属性
兄弟节点可以理解为和本节点处在统一级的节点, .next_sibling属性获取了该节点的写一个兄弟节点, .previous_sibling则与之相反,如果节点不存在,则返回None
注意: 实际文档中的tag的 .next_sibling和.previous_sibling属性通常是字符串或空白,因为空白或者换行也可以被视作一个节点,所以得到的结果可能是空白或者换行
print soup.p.next_sibling # 实际该处为空白 print soup.p.prev_sibling #None 没有前一个兄弟节点,返回 None print soup.p.next_sibling.next_sibling #<p class="story">Once upon a time there were three little sisters; and their names were #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, #<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and #<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; #and they lived at the bottom of a well.</p> #下一个节点的下一个兄弟节点是我们可以看到的节点
(8): 全部兄弟节点
知识点: .next_slibings .previous_siblings 属性
通过 .next_siblings和 .previous_siblings 属性可以对当前节点的兄弟节点迭代输出
for sibling in soup.a.next_siblings: print(repr(sibling)) # u',\n' # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> # u' and\n' # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> # u'; and they lived at the bottom of a well.' # None
(9): 前后节点
知识点: .next_element .previous_element
与 .next_sibling .previous_sibling不同,他并不是针对兄弟节点,而是在所有节点,不分层次
print(soup.head.next_element) # <title>The Dormouse's story</title>
(10): 所有的前后节点
知识点: .next_elements .previous_elements 属性
通过 .next_elements和 .previous_elements的迭代器就可以向前或向后访问文档的解析内容,就好像文档正在被解析一样
for element in last_a_tag.next_elements: print(repr(element)) # u'Tillie' # u';\nand they lived at the bottom of a well.' # u'\n\n' # <p class="story">...</p> # u'...' # u'\n' # None
6.搜索文档树
最常用的是find_all()函数
(1),find_all(name, attrs, recursive, text, **kwargs)
find_all()方法搜索当前tag的所有tag子节点,并判断是否符合过滤条件
1,name参数
name参数可以查找所有名字为name的tag,字符串对象会被自动忽略掉
print(soup.find_all("title")) # [<title>The Dormouse's story</title>] # 第二个参数为匹配的属性 print(soup.find_all("title", class_="sister")) # [<title class="sister">The Dormouse's story</title>] print(soup.find_all("title", "sister")) # [<title class="sister">The Dormouse's story</title>]
A.传字符串
最简单的过滤器是字符串,在搜索方法中传入一个字符串参数,Beautifulsoup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<b>标签
soup.find_all("a") # 查找所有的a标签
B.传正则表达式
如果传入正则表达式作为参数,Beautifulsoup会通过正则表达式的match()来匹配内容,下面的例子找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到
import re for tag in soup.find_all(re.compile("^b")): print(tag.name)
C.传列表
如果传入列表参数,Beautifulsoup会将与列表中任一元素匹配的内容返回,下面代码找到文档中所有<a>标签和<b>标签
soup.find_all(["a", "b"])
D.传入True
True可以匹配任何值,下面代码查找所有tag,但是不会返回字符串节点
E.传方法
如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数[4],如果这个方法返回True表示当前元素匹配并且被找到,如果不是则返回False,下面方法校验了当前元素,如果包含class属性却不包含id属性,那么将返回True:
def has_class_but_no_id(tag): return tag.has_attr("class") and not tag.has_attr("id")
将这个方法作为参数传入find_all()方法,将得到所有<p>标签
soup.find_all(has_class_but_no_id)
keyword参数
注意:如果一个指定名字的参数不是搜索内置的参数名,搜索的参数名,搜索时会把参数当作指定名字tag的属性来搜索,如果包含一个名字为id的参数,BeautifulSoup会搜索每个tag的id属性
soup.find_all(id="link2")
如果传入href参数,BeautifulSoup会搜索每个tag的"href"属性
soup.find_all(href=re.compile("elsie"))
使用多个指定名字的参数可以同时过滤tag的多个属性
soup.find_all(href=re.compile("elsie"), id="link1")
在这里我们想用class过滤,不过class时python的关键字,这怎么办?加个下划线就可以了
soup.find_all("a", class_="sister")
有些tag属性在搜索不能使用,比如HTML5中的data-*属性
data_soup = BeautifulSoup("<div data-foo="value">foo!</div>") data_soup.find_all(data-foo="value")
但是可以通过find_all()方法attrs参数定义一个字典参数来搜索包含特殊属性的tag
data_soup.find_all(attrs={"data-foo": "value"})
text参数
通过text参数可以搜索文档中字符串内容,与name参数可选值一样,text参数接受字符串,正则表达式,列表,True
soup.find_all(text="Elsie") soup.find_all(text=["Title", "Elsie", "Lacie"]) soup.find_all(text=re.compile("Dormouse"))
limit参数
find_all()方法返回全部的搜索结构,如果文档树很大那么搜索会很慢,如果我们不需要全部结果,可以使用limit参数限制返回结果的数量,效果与SQL中的limit关键字类似,当搜索到的结果数量达到limit的限制时,就停止搜索返回结果.
文档书中有3哥tag符合搜索条件,但结果只返回了2个,因为我们限制了返回数量
soup.find_all("a", limit=2)
recursive参数
调用tag的find_all()方法时,Beautifulsoup会检索当前tag的所有子孙节点,如果指向搜索tag的直接子节点,可以使用参数recursive=False.一段简单的文档
<html> <head> <title> The Dormouse's story </title> </head>
是否使用recursive参数的搜索结果
soup.html.find_all("title") soup.html.find_all("title", recursive=False)
(2)find(name=None, attrs={}, recursive=True, text=None, **kwargs)
他与find_all()方法唯一的区别时find_all()方法的返回结果时值包含一个元素的列表,而find()方法直接返回结果
.find("p"), .find All("p"): find返回的时字符串,而且时返回从头查找到第一个tag对,但是如果第一个tag对包括大量内容,父等级很高,则同时其内部包含的,此级标签也都find.findAll返回值是个列表,如果发现一个同名标签内含有多个标签,则内部的标签一并归于该夫标签显示,列表其他元素也不再体现那些内含的同名子标签,即findAll会返回所有的符合要求的结果,并以list返回
(3)find_parents() find_parent()
find_all() 和 find() 只搜索当前节点的所有子节点,孙子节点等. find_parents() 和 find_parent() 用来搜索当前节点的父辈节点,搜索方法与普通tag的搜索方法相同,搜索文档搜索文档包含的内容
(4)find_next_siblings() find_next_sibling()
这2个方法通过 .next_siblings 属性对当 tag 的所有后面解析的兄弟 tag 节点进行迭代, find_next_siblings() 方法返回所有符合条件的后面的兄弟节点,find_next_sibling() 只返回符合条件的后面的第一个tag节点
(5)find_previous_siblings() find_previous_sibling()
这2个方法通过 .previous_siblings 属性对当前 tag 的前面解析的兄弟 tag 节点进行迭代, find_previous_siblings()方法返回所有符合条件的前面的兄弟节点, find_previous_sibling() 方法返回第一个符合条件的前面的兄弟节点
(6)find_all_next() find_next()
这2个方法通过 .next_elements 属性对当前 tag 的之后的 tag 和字符串进行迭代, find_all_next() 方法返回所有符合条件的节点, find_next() 方法返回第一个符合条件的节点
(7)find_all_previous()和find_previous()
这2个方法通过 .previous_elements 属性对当前节点前面的 tag 和字符串进行迭代, find_all_previous() 方法返回所有符合条件的节点, find_previous()方法返回第一个符合条件的节点
7.CSS选择器
用到的方法就是soup.select(),返回的类型时list
1,通过标签名查找
print(soup.select("title"))
2,通过类名查找
print(soup.select(".select"))
3,通过id名查找
print(soup.select(#link1))
4,组合查找
组合查找即写class文件时,标签名与类名,id名进行的组合原理一样,例如: 查找p标签中,id等于link的内容,二者需要用空格分开
print(soup.select("p #link1"))
直接子标签查找
print(soup.select("head > title"))
5,属性查找
查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到
print(soup.select(a[class="sister"]))
同样,属性仍然可以与上述查找方式组合,不再同一节点的空格隔开,同一节点的不加空格
print(soup.select("p a[href="http://example.com/elsie"]"))
以上的select方法返回的结果都是列表形式,可以遍历形式输出,然后用get_text()方法来获取他的内容

浙公网安备 33010602011771号