zoukankan      html  css  js  c++  java
  • python 爬虫5 Beautiful Soup的用法

    1.创建 Beautiful Soup 对象

    from bs4 import BeautifulSoup
    
    html = """
    <html><head><title>The Dormouse's story</title></head>
    <body>
    <p class="title" name="dromouse"><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>
    """
    
    soup = BeautifulSoup(html)
    print soup.prettify()

    2.四大对象种类

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

    • Tag
    • NavigableString
    • BeautifulSoup
    • Comment

    2.1 tag

    print soup.title
    #<title>The Dormouse's story</title>
    
    print soup.head
    #<head><title>The Dormouse's story</title></head>
    
    print soup.a
    #<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
    
    print soup.p
    #<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

    2.2 name

    print soup.name
    #[document]
    
    print soup.head.name
    #head

    2.3 attrs

    print soup.p.attrs
    #{'class': ['title'], 'name': 'dromouse'}
    print soup.p['class']
    #['title']
    
    print soup.p.get('class')
    #['title']
    
    //可以进行修改和删除
    soup.p['class']="newClass"
    print soup.p
    #<p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
    
    del soup.p['class']
    print soup.p
    #<p name="dromouse"><b>The Dormouse's story</b></p>

    (2)NavigableString

    print soup.p.string
    #The Dormouse's story

    3.搜索文档树

    (1)find_all( name , attrs , recursive , text , **kwargs )

    find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件

    1)name 参数

    name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉

    A.传字符串

    最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<b>标签

    print soup.find_all('a')
    #[<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>]

    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">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>]

    D.传 True

    True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点

    for tag in soup.find_all(True):
        print(tag.name)
    # html
    # head
    # title
    # body
    # p
    # b
    # p
    # a
    # a

    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')
    
    print 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>]

    2)keyword 参数

    soup.find_all(id='link2')
    # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
    
    soup.find_all(href=re.compile("elsie"))
    # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
    
    soup.find_all(href=re.compile("elsie"), id='link1')
    # [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
    
    soup.find_all("a", class_="sister")
    # [<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>]

    有些tag属性在搜索不能使用,比如HTML5中的 data-* 属性 ,但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag

    data_soup.find_all(attrs={"data-foo": "value"})
    # [<div data-foo="value">foo!</div>]
  • 相关阅读:
    有耗介质中波的传播
    介质分界处的反射
    TFSF边界条件
    吸收边界条件
    .apk的MIME类型
    Java instanceof
    Java toString()方法的自动调用
    整理一系列优秀的Android开发源码
    GOOGLE CODE ANDROID 开源项目 集合
    imsdroid 学习(初认识)
  • 原文地址:https://www.cnblogs.com/alamZ/p/7059759.html
Copyright © 2011-2022 走看看