天天看點

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/'
           

繼續閱讀