美文网首页
BeautifulSoup学习笔记(一)

BeautifulSoup学习笔记(一)

作者: Kimmygogo | 来源:发表于2018-01-20 21:23 被阅读0次

    学习资料 Beautiful Soup4.2.0文档
    环境:Python3.6


    Beautiful Soup又称为美丽汤,是一个可以从html或xml文件中提取数据的python库。先来看个例子

    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 sister; and their names were
    <a href = "http://example.com/elisie" class = "sister" id = "link1">Elisie</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>
    """
    #从bs4库中导入美丽汤
    from bs4 import BeautifulSoup
    #做一锅汤咯
    soup = BeautifulSoup(html_doc,'html.parser')
    #按缩进打印soup
    print(soup.prettify())
    #浏览结构化数据的方法
    soup.title # 浏览title标签
    soup.title.name # title标签的标签吗
    soup.title.string # 浏览title标签中的字符串
    soup.title.parent.name # 查看title标签父标签的标签名
    soup.p #查看第一个p标签
    soup.p['class'] #查看第一个p标签的属性名为'class'的属性值,其操作和字典一样
    soup.a # 查看第一个a标签
    soup.findAll('a') # 查看所有的a标签
    soup.find(id = 'link3') #查看id属性值为'link3'的标签
    # 从文档中找到所有a标签的链接
    for link in soup.findAll('a'):
        print(link.get('href')) #或者print(link['href'])
    # 从文档中获取所有的文字内容
    print(soup.get_text())
    

    安装Beautiful Soup

    如果你的系统是Debain或ubuntu,那么可以通过系统的软件包管理来安装
    $ apt-get install Python3-bs4
    如果不能通过系统安装,可以使用pip或easy_install来安装。包的名字叫beautifulsoup4,兼容Python2和Python3.
    $ easy_install beautifulsoup4
    $ pip install beautifulsoup4
    如果上面的方法都没有用,那么你可以将bs4包打包放入你的项目中,那样无须安装只要导入即可使用。

    安装解析器

    bs4库支持Python标准库中的html解析器,还支持一些第三方的解析器,其中一个是lxml。根据操作系统不同,可以选择下列方法来安装lxml:

    $ apt-get install Python-lxml
    $ easy_install lxml
    $ pip install lxml

    另外一个可供选择的解析器是纯Python实现的html5lib,html5lib的解析方式与浏览器相同,可以选择下列方法来安装html5lib:

    $ apt-get install Python-html5lib
    $ easy_install html5lib
    $ pip install html5lib

    下表列出了主要的解析器,以及他们的优缺点:
    <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
    $$S=\pi r^2$$

    解析器 使用方法 优势 劣势
    Python标准库 BeautifulSoup(markup,"html.parser") 1. Python的内置标准库
    2. 执行速度适中
    3. 文档容错能力强
    Python2.7.3or3.2.2前的版本中文档容错能力差
    lxml html解析器 BeautifulSoup(markup,"lxml") 1. 速度快
    2.文档容错能力强
    需要安装C语言库
    lxml xml解析器 BeautifulSoup(markup,["lxml","xml"]) 1.速度快
    2.唯一只是xml的解析器
    需要安装C语言库
    html5lib BeautifulSoup(markup,"html5lib") 1.最好的容错性
    2.以浏览的方式解析文档
    3.生成html5格式的文档
    1.速度慢
    2.不依赖外部扩展

    提示:如果一段html或xml文档格式不正确的话,那么在不同的解析器中返回的结果可能是不一样的。

    如何使用

    将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象,可以传入一段字符串或一个文件。

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(open("index.html"))
    soup = BeautifulSoup("<html>data</html>")
    

    对象的种类

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

    Tag


    Tag对象与html原生文档中的Tag相同:

    soup = BeautifulSoup('<b class = "boldest">Extremly bold</b>')
    tag = soup.b
    type(tag)
    

    Tag有很多方法和属性,其中最重要的为name和attributes.

    1. Name
      每个tag都有自己的名字,通过.name来获取
      tag.name
      如果改变了tag的name,那将影响所有通过当前BeautifulSoup对象生成的html文档:
    tag.name = "blockquote"
    tag
    
    1. Attributes
      一个tag可能有很多属性。tag <b class = "boldest">有一个class的属性,值为"boldest" tag的属性的操作方法与字典相同:
    tag['class']
    # 'boldest'
    

    也可以直接用attrs方法取出属性及对应的属性值

    tag.attrs
    # {"class":"boldest"}
    

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

    tag['class'] = 'very bold'
    tag['id']= 1
    tag
    # <blockquote class = "very bold" id = "1">Extremely bold</blockquote>
    del tag['class']
    del tag['id']
    tag 
    <blockquote>Extremely bold</blockquote>
    tag['class']
    # KeyError:'class'
    

    NavigableString


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

    tag中包含的字符串不能编辑但是能够替换,用replace_with()方法:

    tag.string.replace_with("No longer bold")
    tag
    # <blockquote>No longer bold</blockquote>
    

    NavigableString对象支持遍历文档树和搜索文档树中定义的大部分属性,并非全部。尤其是,一个字符串不能包含其他内容(tag能够包含字符串或是其他tag),字符串不支持.contents或.string属性的find()方法。
    如果想在BeautifulSoup之外使用NavigableString对象,需要调用str()

    BeautifulSoup


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

    soup.name
    # '[document]'
    

    Comment


    Tag, NavigableString, BeautifulSoup几乎覆盖了html和xml中的所有内容,但是有些特殊的对象,容易让人担心的内容是文档的注释部分:

    markup = "<b><!--Hey, buddy. want to buy a used parser?--></b>"
    soup = BeautifulSoup(markup,'html.parser')
    comment = soup.b.string
    type(comment)
    # <class 'bs4.element.comment'>
    

    Comment是一个特殊类型的NavigableString对象。

    遍历文档树

    还拿"爱丽丝梦游仙境"的文档来做例子:

    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 sister; and their names were
    <a href = "http://example.com/elisie" class = "sister" id = "link1">Elisie</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>
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html_doc,'html.parser')
    

    通过这段例子来演示怎样从文档的一段内容找到另一段内容。

    今天先写到这里,未完待续...

    相关文章

      网友评论

          本文标题:BeautifulSoup学习笔记(一)

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