zoukankan      html  css  js  c++  java
  • Python3.x的BeautifulSoup解析html常用函数

    Python3.x的BeautifulSoup解析html常用函数

    1,初始化:

    soup = BeautifulSoup(html) # html为html源代码字符串,type(html) == str

    2,用tag获取相应代码块的剖析树:

    #当用tag作为搜索条件时,我们获取的包含这个tag块的剖析树:
    #<tag><xxx>ooo</xxx></tag>
    #这里获取head这个块
    head = soup.find('head')
    # or
    # head = soup.head
    # or
    # head = soup.contents[0].contents[0]

    contents属性是一个列表,里面保存了该剖析树的直接儿子,如:

    html = soup.contents[0] # <html> ... </html>
    head = html.contents[0] # <head> ... </head>
    body = html.contents[1] # <body> ... </body>

    3,用contents[], parent, nextSibling, previousSibling寻找父子兄弟tag:

      beautifulSoup提供了几个简单的方法直接获取当前tag块的父子兄弟。

     假设我们已经获得了body这个tag块,我们想要寻找<html>, <head>, 第一个<p>, 第二个<p>这四个tag块:

    # body = soup.bodyhtml = body.parent # html是body的父亲
    head = body.previousSibling # head和body在同一层,是body的前一个兄弟
    p1 = body.contents[0] # p1, p2都是body的儿子,我们用contents[0]取得p1
    p2 = p1.nextSibling # p2与p1在同一层,是p1的后一个兄弟, 当然body.content[1]也可得到
    
    print(p1.text)
    # u'This is paragraphone.'
    print(p2.text)
    # u'This is paragraphtwo.'
    #  注意:1,每个tag的text包括了它以及它子孙的text。2,所有text已经被自动转
    #为unicode,如果需要,可以自行转码encode(xxx)

    4,用find, findParent, findNextSibling, findPreviousSibling寻找祖先或者子孙 tag:

      find方法(我理解和findChild是一样的),就是以当前节点为起始,遍历整个子树,找到后返回。

     而这些方法的复数形式,会找到所有符合要求的tag,以list的方式放回。他们的对应关系是:find->findall, findParent->findParents, findNextSibling->findNextSiblings...,如:

    print soup.findAll('p')
    # [<p id="firstpara" align="center">This is paragraph <b>one</b>.</p>, <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>]

    5,find的几种用法,其他的类比: find(name=None, attrs={}, recursive=True, text=None, **kwargs),文档参考:          https://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html#The%20basic%20find%20method:%20findAll%28name,%20attrs,%20recursive,%20text,%20limit,%20**kwargs%29)

     (1).搜索tag:

    find(tagname)        # 直接搜索名为tagname的tag 如:find('head')
    find(list)           # 搜索在list中的tag,如: find(['head', 'body'])
    find(dict)           # 搜索在dict中的tag,如:find({'head':True, 'body':True})
    find(re.compile('')) # 搜索符合正则的tag, 如:find(re.compile('^p')) 搜索以p开头的tag
    find(lambda)         # 搜索函数返回结果为true的tag, 如:find(lambda name: if len(name) == 1) 搜索长度为1的tag
    find(True)           # 搜索所有tag

     (2),搜索属性(attrs):

    find(id='xxx')                                  # 寻找id属性为xxx的
    find(attrs={id=re.compile('xxx'), algin='xxx'}) # 寻找id属性符合正则且algin属性为xxx的
    find(attrs={id=True, algin=None})               # 寻找有id属性但是没有algin属性的

     (3),搜索文字(text):

               注意:文字的搜索会导致其他搜索给的值如:tag, attrs都失效。

                    方法与搜索tag一致;

     (4),recursive, limit:

          recursive=False表示只搜索直接儿子,否则搜索整个子树,默认为True。

         当使用findAll或者类似返回list的方法时,limit属性用于限制返回的数量,如findAll('p', limit=2): 返回首先找到的两个tag

  • 相关阅读:
    Asp.Net2.0中的缓存
    webpartzone无法显示最小化和关闭按钮?
    TransactionScope分布式事务和非分布式事务
    JS获取GET参数的两种方法
    js 文件上传下载功能
    android动态设置布局LayoutInflater的使用详解
    Eclipse大括号换行显示
    Java强引用、 软引用、 弱引用、虚引用(转载)
    Android扭曲图像(水面落叶壁纸初步实现)
    win7系统自带的屏幕录制软件
  • 原文地址:https://www.cnblogs.com/lizm166/p/8137046.html
Copyright © 2011-2022 走看看