天天看点

python BeautifulSoup使用小记

                                              python BeautifulSoup使用小记

    注:最近在使用BeautifulSoup 进行HTML解析,记一笔~

一、BeautifulSoup一些用法规则

1.导入BeautifulSoup模块

from BeautifulSoup import BeautifulSoup
           

2.获取BeautifulSoup对象

soup=BeautifulSoup(str) 
           

3.通过ID获取指定对象

soup.find(id='newscontent')  #返回id='newscontent'的第一个可匹配对象
           
soup.findAll(id='newscontent') #返回id='newscontent'的所有Tag以及NavigableString
           

4.通过class属性获取指定对象

soup.find(attrs={'class':'pagelink'}) #返回class='pagelink'的第一个可匹配对象
           

5.通过Tag获取指定对象

soup.find('em')   #<em>one</em>

soup.findAll('em') #获取所有的<em>标签

soup.findAll('em')[0] #获取所有<em>标签中的第一个<em>标签

#获取 与所有<em>标签中的第一个<em>标签并列的下面所有的<dd>标签
soup.findAll('em')[0].findAllNext('dd') 
           

如果一个标签只有一个子节点且是字符串类型,这个子节点可以这样访问 

tag.string

,等同于

tag.contents[0]

的形式

soup.find('em').string      #<em>one</em> ->one
           

通过get()方法获取tag对应的属性值

soup.find('a').get('href') #<a href='http://cn.bing.com/'> </a> -> 'http://cn.bing.com/'
           

继续阅读