• Beautifulsoup学习笔记


    1.导入beautifulsoup

    from BeautifulSoup import BeautifulSoup 

    2.实例化一个soup对象

    html="<html></html>"
    soup = BeautifulSoup(html)

    html的字符串可以通过打开本地文件或者抓取网络的html来得到

    测试用的html是:

    3.beautifulsoup对象

    会有三种beautifulsoup对象

    1).soup对象

    print type(soup)
    
    <class 'BeautifulSoup.BeautifulSoup'>

    2).Tag对象(标签对象)

    print type(soup.html)
    
    <class 'BeautifulSoup.Tag'>

    3).string对象

    print type(soup.div.string)
    
    <class 'BeautifulSoup.NavigableString'>

    4.剖析soup

      1).通过标签

    soup=BeautifulSoup(htm)
    print soup.html
    print soup.body
    print soup.p

    可以直接通过tag获取到html,但是只会返回第一个匹配到的标签,例如有两个<p>标签,用soup.p只会返回第一个

    这种方法返回的为Tag对象

      2)contents,parent

    也可以通过contents获取子元素,返回的是list,例如soup.contents[0],返回的是html节点,soup.contents[0].centents 是一个包含head标签和body标签的的列表。

    奇怪的是len(soup.contents[0].contents),是等于5的,除了head标签和body标签外,还会有三个空元素

    使用contents向后遍历树,使用parent向前遍历树

      3)next 返回子元素

    print soup.div.next
    
    i am div1

      4)findAll

    搜索提供了两个方法,一个是 find,一个是findAll。这里的两个方法(findAll和 find)仅对Tag对象以及,顶层剖析对象有效,但 NavigableString不可用。

      findAll(name, attrs, recursive, text, limit, **kwargs)

    soup.findAll('div')
    
    [<div id="div1">i am div1</div>, <div id="div2">i am div2</div>]
    print soup.findAll('div',id='div1')
    
    [<div id="div1">i am div1</div>]
    print soup.findAll('div',{'id':'div2'})
    
    [<div id="div2">i am div2</div>]

    可以以字典的形式传入attrs

    pat=re.compile('divd+')
    print soup.findAll('div',{'id':pat})
    
    [<div id="div1">i am div1</div>, <div id="div2">i am div2</div>]

    也可以用正则匹配

     5.修改属性

    pat=re.compile('divd+')
    a=soup.findAll('div',{'id':pat})[0]
    a['id']='ddd'
    print a

    修改a标签的id属性

    6.访问属性

    a['id']

    可以以这种方法去访问属性

    7.demo,剖析职级的网页,将所有需要的行为举证整理成一个excel文件

    #encoding=utf-8
    __author__ = 'kevinlu1010@qq.com'
    import re
    from BeautifulSoup import BeautifulSoup
    f=open('index.htm','r')
    htm=f.read()
    f.close()
    soup=BeautifulSoup(htm)
    
    pat=re.compile('.+')
    pat1=re.compile('行为证明'.decode('utf-8'))
    btns=soup.findAll('button',{'popover':pat,'popover-title':pat1})
    
    mybtn=[]
    for btn in btns:
        mybtn.append(btn['popover'].replace('
    ','').replace('<br>',';').replace('<br />',';'))
    for b in mybtn:
        print b

    参考:http://www.leeon.me/upload/other/beautifulsoup-documentation-zh.html

    http://rsj217.diandian.com/post/2012-11-01/40041235132

  • 相关阅读:
    Android 蓝牙4.0 BLE (onServicesDiscovered 返回 status 是 129,133时)
    Android 读取蓝牙设备信息开发
    Android RxJava
    Android 通信 EventBus
    数据仓库基础介绍
    探索SQL Server元数据(三):索引元数据
    探索SQL Server元数据(二)
    MySQL常见备份方案
    hivesql优化的深入解析
    mysql执行计划看是否最优
  • 原文地址:https://www.cnblogs.com/Xjng/p/3892882.html
Copyright © 2020-2023  润新知