爬虫系列11.BS4遍历文档树

子节点:
tag名字:
soup.head soup.title,支持链式调用,soup.body.b,只能获取当前名字的第一个tag
如果想获得所有的子节点,调用find_all()方法;soup.find_all(‘a’)

tag属性:
    .contents:将tag的直接子节点,不包含孙子辈一列表的形式输出
    .children:生成器,可以对tag的子节点,直接子节点,不包含孙子辈,进行循环 
        for child in title_tag.children:
            print(child)

    .descendants:可以对多有的tag子孙节点进行递归循环:
        for child in head_tag.descendants:
            print(child)
            # <title>The Dormouse's story</title>
            # The Dormouse's story
    .string
        1.如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点
        2.如果一个tag仅有一个子节点,那么这个tag也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同
        3.如果tag包含了多个子节点,tag就无法确定 .string 方法应该调用哪个子节点的内容, .string 的输出结果是 None :

    .strings 和 stripped_strings:
        如果tag中包含多个字符串 [2] ,可以使用 .strings 来循环获取:
        for string in soup.strings:
            print(repr(string))
        输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容
        for string in soup.stripped_strings:
            print(repr(string))

父节点:
每个tag或字符串都有父节点:被包含在某个tag中
.parent
只是父节点。
文档的顶层节点比如的父节点是 BeautifulSoup 对象;
BeautifulSoup 对象的 .parent 是None;
.parents
通过元素的 .parents 属性可以递归得到元素的所有父辈节点,下面的例子使用了 .parents 方法遍历了标签到根节点的所有节点.
link = soup.a
link
#
Elsie
for parent in link.parents:
if parent is None:
print(parent)
else:
print(parent.name)

兄弟节点:
sibling_soup = BeautifulSoup(“text1text2”)
print(sibling_soup.prettify())

.next_sibling 后一个  和 .previous_sibling 前一个,没有返回None
实际文档中的tag的 .next_sibling 和 .previous_sibling 属性通常是字符串或空白.

.next_siblings 和 .previous_siblings 对兄弟节点进行迭代输出
for sibling in soup.a.next_siblings:
    print(repr(sibling))

回退和前进:
The Dormouse’s story

The Dormouse’s story

HTML解析器把这段字符串转换成一连串的事件: “打开<html>标签”,”打开一个<head>标签”,”打开一个<title>标签”,”添加一段字符串”,”关闭<title>标签”,”打开<p>标签”,等等.Beautiful Soup提供了重现解析器初始化过程的方法.

.next_element 和 .previous_element
.next_element 属性指向解析过程中下一个被解析的对象(字符串或tag),空白处也要解析,换行符

.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'

搜索文档树(find与find_all,tag)
过滤器:
字符串
最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的标签:
soup.find_all(‘b’)
# [The Dormouse’s story]

正则表达式:
    如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示<body>和<b>标签都应该被找到
    import re
    for tag in soup.find_all(re.compile("^b")):
        print(tag.name)
    # body
    # b

列表:
如果传入列表参数,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">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

True
True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点
for tag in soup.find_all(True):
    print(tag.name)
    # html
    # head
    # title
    # body

方法:
    如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 [4] ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
    下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性,那么将返回 True
    def has_class_but_no_id(tag):
        return tag.has_attr('class') and not tag.has_attr('id')
        soup.find_all(has_class_but_no_id)


    通过一个方法来过滤一类标签属性的时候, 这个方法的参数是要被过滤的属性的值, 而不是这个标签. 下面的例子是找出 href 属性不符合指定正则的 a 标签.
    def not_lacie(href):
        return href and not re.compile("lacie").search(href)
    soup.find_all(href=not_lacie)

    标签过滤方法可以使用复杂方法. 下面的例子可以过滤出前后都有文字的标签.
    from bs4 import NavigableString
    def surrounded_by_strings(tag):
        return (isinstance(tag.next_element, NavigableString)
                and isinstance(tag.previous_element, NavigableString))

    for tag in soup.find_all(surrounded_by_strings):
        print tag.name
    # p

find_all()方法
find_all( name , attrs , recursive , string , **kwargs )
name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉.
重申: 搜索 name 参数的值可以使任一类型的 过滤器 ,字符窜,正则表达式,列表,方法或是 True 
keyword 参数
如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性.
搜索指定名字的属性时可以使用的参数值包括 字符串 , 正则表达式 , 列表, True .
    如果传入 href 参数,Beautiful Soup会搜索每个tag的”href”属性:
    soup.find_all(href=re.compile("elsie"))
    # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
使用多个指定名字的参数可以同时过滤tag的多个属性:
    soup.find_all(href=re.compile("elsie"), id='link1')
有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性:
    data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
    data_soup.find_all(data-foo="value")
    # SyntaxError: keyword can't be an expression
但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag:
    data_soup.find_all(attrs={"data-foo": "value"})
    # [<div data-foo="value">foo!</div>]

按CSS搜索:
按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 class 在Python中是保留字,使用 class 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 class_ 参数搜索有指定CSS类名的tag:
    soup.find_all("a", class_="sister")
    class_ 参数同样接受不同类型的 过滤器 ,字符串,正则表达式,方法或 True :
    def has_six_characters(css_class):
    return css_class is not None and len(css_class) == 6
    soup.find_all(class_=has_six_characters)
    完全匹配 class 的值时,如果CSS类名的顺序与实际不符,将搜索不到结果
    css_soup.find_all("p", class_="body strikeout")
    # [<p class="body strikeout"></p>]

string 参数
通过 string 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, string 参数接受 字符串 , 正则表达式 , 列表, True . 看例子:
soup.find_all(string=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"]

find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.
soup.find_all("a", limit=2)
recursive 参数
调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .

像调用 find_all() 一样调用tag
下面两行代码是等价的:
soup.find_all("a")
soup("a")

soup.title.find_all(string=True)
soup.title(string=True)

find()
find( name , attrs , recursive , string , **kwargs )
find_all() 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.比如文档中只有一个标签,那么使用 find_all() 方法来查找标签就不太合适, 使用 find_all 方法并设置 limit=1 参数不如直接使用 find() 方法.下面两行代码是等价的:
唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果.
find_all() 方法没有找到目标是返回空列表, find() 方法找不到目标时,返回 None .

soup.head.title 是 tag的名字 方法的简写.这个简写的原理就是多次调用当前tag的 find() 方法:
soup.find(“head”).find(“title”)

find_parents() 和 find_parent()
.parent 和 .parents 属性
find_parents( name , attrs , recursive , string , **kwargs )
find_parent( name , attrs , recursive , string , **kwargs )

find_next_siblings() 和 find_next_sibling()
.next_siblings 属性
find_next_siblings( name , attrs , recursive , string , **kwargs )
find_next_sibling( name , attrs , recursive , string , **kwargs )

find_previous_siblings() 和 find_previous_sibling()
.previous_siblings 属性
find_previous_siblings( name , attrs , recursive , string , **kwargs )
find_previous_sibling( name , attrs , recursive , string , **kwargs )

find_all_next() 和 find_next()
.next_elements 属性
find_all_next( name , attrs , recursive , string , **kwargs )
find_next( name , attrs , recursive , string , **kwargs )

find_all_previous() 和 find_previous()
find_all_previous( name , attrs , recursive , string , **kwargs )
find_previous( name , attrs , recursive , string , **kwargs )
.previous_elements 属性

CSS选择器
在 Tag 或 BeautifulSoup 对象的 .select() 方法中传入字符串参数, 即可使用CSS选择器的语法找到tag:
soup.select(“title”)
通过tag标签逐层查找:
soup.select(“html head title”)
找到某个tag标签下的直接子标签:
soup.select(“head > title”)
找到兄弟节点标签:
soup.select(“#link1 ~ .sister”)
# [Lacie,
# Tillie]
soup.select(“#link1 + .sister”)
# [Lacie]
通过CSS的类名查找:
soup.select(“.sister”)
通过tag的id查找:
soup.select(“a#link2”)
同时用多种CSS选择器查询元素:
soup.select(“#link1,#link2”)
通过是否存在某个属性来查找:
soup.select(‘a[href]’)
通过属性的值来查找:
soup.select(‘a[href=”http://example.com/elsie”]’)
返回查找到的元素的第一个:
soup.select_one(“.sister”)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆豆orz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值