美文网首页
BeautifulSoup4简易食用指南

BeautifulSoup4简易食用指南

作者: ProkillerJ | 来源:发表于2017-03-01 22:25 被阅读156次

    本文是对BeautifulSoup4官方文档的简化与填坑

    Beautifulsoup4

    1.安装

    1.1安装Beautiful Soup4

    利用python包管理工具pip可以十分简单的安装Beautiful Soup4

    $ pip install beautifulsoup4 
    

    1.2安装第三方解析器lxml提高运行效率

    Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml .
    安装方法

    $ pip install lxml
    

    PS: win下安装lxml有坑,如果pip安装报错,参考StackOverflow上提供的解决方法

    2.使用方法

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(open("index.html"))
    print(soup.prettify())
    

    首先,文档被转换成Unicode,并且HTML的实例都被转换成Unicode编码。然后,Beautiful Soup选择最合适的解析器来解析这段文档,如果手动指定解析器那么Beautiful Soup会选择指定的解析器来解析文档

    2.1 Beautiful Soup的对象

    Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment .

    Tag

    Tag 对象与XML或HTML原生文档中的tag相同:

    soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
    tag = soup.b
    type(tag)
    # <class 'bs4.element.Tag'>
    

    Tag中有name和attributes属性

    tag.name
    # u'b'
    tag['class']
    # u'boldest'
    

    tag的属性可以被添加,删除或修改. 再说一次, tag的属性操作方法与字典一样

    NavigableString(可以遍历的字符串)

    字符串常被包含在tag内.Beautiful Soup用 NavigableString 类来包装tag中的字符串:

    tag.string
    # u'Extremely bold'
    type(tag.string)
    # <class 'bs4.element.NavigableString'>
    

    一个 NavigableString字符串与Python中的Unicode字符串相同,并且还支持包含在 遍历文档树搜索文档树 中的一些特性. 通过 unicode()方法可以直接将 NavigableString对象转换成Unicode字符串:

    unicode_string = unicode(tag.string)
    unicode_string
    # u'Extremely bold'
    type(unicode_string)
    # <type 'unicode'>
    
    BeautifulSoup

    BeautifulSoup
    对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag
    对象,它支持 遍历文档树搜索文档树 中描述的大部分的方法.
    因为 BeautifulSoup对象并不是真正的HTML或XML的tag,所以它没有name和attribute属性.但有时查看它的 .name属性是很方便的,所以 BeautifulSoup对象包含了一个值为 “[document]” 的特殊属性 .name

    soup.name
    # u'[document]'
    
    Comment(注释及特殊字符串)

    Tag , NavigableString , BeautifulSoup 几乎覆盖了html和xml中的所有内容,但是还有一些特殊对象.容易让人担心的内容是文档的注释部分
    PS:由于爬虫一般不需要爬注释,不展开。

    2.2 遍历文档树

    PS:树,好大的树

    获取标签内容:

    获取标签内容和剥洋葱差不多

    soup = '''
    <head><title>The Dormouse's story</title></head>
    <title>Another Dormouse's story</title>
    '''
    soup.head
    # <head><title>The Dormouse's story</title></head>
    soup.head.title
    # <title>The Dormouse's story</title>
    soup.title 
    # <title>The Dormouse's story</title>
    soup.title.string
    The Dormouse's story
    

    可以看到使用title只能获取到第一个title,可以用find_all()需要获取所有title,并返回一个list:

    soup.find_all('title')
    # [<title>The Dormouse's story</title>,<title>Another Dormouse's story</title>]
    
    
    .contents ,.children,.descendants:

    .contents 和 .children 属性仅包含tag的直接子节点
    .contents 属性相当于剥一层洋葱皮,并返回list:

    head_tag = '''
    <head><title>The Dormouse's story</title><title>Another Dormouse's story</title></head>
    '''
    head_tag.content
    # [<title>The Dormouse's story</title>, <title>Another Dormouse's story</title>]
    

    .children是列表迭代器,用for输出:

    html_doc = """<head><title>The Dormouse's story</title><title>T Dormouse's story</title></head>"""
    
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html_doc,'lxml')
    
    print(soup.head.children)
    for child in soup.head.children:
        print(child)
    # <list_iterator object at 0x10b66c710>
    # <title>The Dormouse's story</title>
    # <title>T Dormouse's story</title> 
    

    .descendants 属性和.children类似,不同的是.children只能访问一层子节点,而可以对所有tag的子孙节点进行递归循环

    .strings 和以及更好的 stripped_strings

    如果tag中包含多个字符串 ,可以使用 .strings来循环获取,stripped_strings用于去除所有空白内容,包括段落间空行:

    .parent和.parents

    .parent 属性可以用来获取某个元素的父节点,.parents 属性可以递归得到元素的所有父辈节点

    兄弟节点

    .next_sibling 和 .previous_sibling,.next_siblings 和 .previous_siblings:

    在文档树中,使用 .next_sibling 和 .previous_sibling 属性来查询兄弟节点,通过 .next_siblings 和 .previous_siblings 属性可以对当前节点的兄弟节点迭代输出:

    回退和前进

    .next_element 和 .previous_element,.next_elements 和 .previous_elements

    .next_element 属性指向解析过程中下一个被解析的对象(字符串或tag),结果可能与 .next_sibling 相同,但通常是不一样的.通过 .next_elements 和 .previous_elements 的迭代器就可以向前或向后访问文档的解析内容,就好像文档正在被解析一样.

    2.3搜索文档树

    find_all()

    使用 find_all() 类似的方法可以查找到想要查找的文档内容,find_all( name , attrs , recursive , text , **kwargs )

    • name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉.
    • 如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性.搜索指定名字的属性时可以使用的参数值包括 字符串 , 正则表达式 , 列表, True .
    • 按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 class 在Python中是保留字,使用 class 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 class_ 参数搜索有指定CSS类名的tag:
    • 通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True . 看例子:
    • find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.
    • 调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False
    find_all('b')
    # 返回所有b标签
    
    
    import re
    for tag in soup.find_all(re.compile("^b")):
        print(tag.name)
    # body
    # b
    # 通过正则表达式返回含有b开头的标签
    
    
    soup.find_all(["a", "b"])
    # 返回含有a或b标签的
    
    
    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)
    # [<p class="title"><b>The Dormouse's story</b></p>,
    #  <p class="story">Once upon a time there were...</p>,
    #  <p class="story">...</p>]
    # 自定一种方法
    
    
    

    find()

    find('tag')相当于find_all('tag',limit = 1)

    find_next_siblings() 合 find_next_sibling(),find_previous_siblings() 和 find_previous_sibling()

    find_next_siblings( name , attrs , recursive , text , **kwargs )
    find_next_sibling( name , attrs , recursive , text , **kwargs )
    这2个方法通过 .next_siblings 属性对当tag的所有后面解析 [5] 的兄弟tag节点进行迭代, find_next_siblings() 方法返回所有符合条件的后面的兄弟节点, find_next_sibling() 只返回符合条件的后面的第一个tag节点.
    ind_previous_siblings( name , attrs , recursive , text , **kwargs )
    find_previous_sibling( name , attrs , recursive , text , **kwargs )
    这2个方法通过 .previous_siblings 属性对当前tag的前面解析 [5] 的兄弟tag节点进行迭代, find_previous_siblings() 方法返回所有符合条件的前面的兄弟节点, find_previous_sibling() 方法返回第一个符合条件的前面的兄弟节点

    find_all_next() 和 find_next(),find_all_previous() 和 find_previous()

    find_all_next( name , attrs , recursive , text , **kwargs ),find_next( name , attrs , recursive , text , **kwargs )
    这2个方法通过 .next_elements 属性对当前tag的之后的tag和字符串进行迭代, find_all_next() 方法返回所有符合条件的节点, find_next() 方法返回第一个符合条件的节点
    find_all_previous( name , attrs , recursive , text , **kwargs ),find_previous( name , attrs , recursive , text , **kwargs )
    这2个方法通过 .previous_elements 属性对当前节点前面 [5] 的tag和字符串进行迭代, find_all_previous() 方法返回所有符合条件的节点, find_previous() 方法返回第一个符合条件的节点.

    2.4 CSS选择器

    W3School上有关CSS选择器相关介绍

    2.5 修改文档树

    由于目前我接触到的爬虫都很少涉及到修改数据,有需要自行参看Beautifulsoup官方文档

    2.6 输出

    get_text()

    如果只想得到tag中包含的文本内容,那么可以嗲用 get_text() 方法,这个方法获取到tag中包含的所有文版内容包括子孙tag中的内容,并将结果作为Unicode字符串返回:

    PS:其他内容请查看官方文档

    相关文章

      网友评论

          本文标题:BeautifulSoup4简易食用指南

          本文链接:https://www.haomeiwen.com/subject/axicgttx.html