Python爬蟲--beautifulsoup 4 用法

Beautiful Soup將複雜HTML文檔轉換成一個複雜的樹形結構,css

每一個節點都是Python對象,全部對象能夠概括爲4種: Tag , NavigableString , BeautifulSoup , Comment html

 

1、Tag:python

Tag對象與XML或HTML原生文檔中的tag相同,Tag有不少方法和屬性,最重要的是name和attributesspa

soup = BeautifulSoup('<b class="boldest">Extremely bold</b>') tag = soup.b type(tag)

   name:code

      每一個Tag都有本身名字,經過.name來獲取xml

      tag.namehtm

      也能夠改變這個名字,將影響全部經過當前Beautiful Soup對象生成的HTML文檔:對象

      tag.name = "blockquote"    #會改變它的名字utf-8

   attribute:element

      

      一個tag可能有不少個屬性. tag <b class="boldest"> 有一個 「class」 的屬性,

      值爲 「boldest」 . tag的屬性的操做方法與字典相同:

      tag['class']

      也能夠直接」點」取屬性, 好比: .attrs :

      tag.attrs
Tag的屬性操做方法與字典同樣,也是鍵對應值,能夠向下面同樣
tag['class'] = 'verybold' tag['id'] = 1 tag        # <blockquote class="verybold" id="1">Extremely bold</blockquote>

還能夠刪除:
del tag['class'] del tag['id'] tag        # <blockquote>Extremely bold</blockquote>

刪除了就沒有了:
tag['class'] # KeyError: 'class' print(tag.get('class')) # None

    多值屬性
HTML 4定義了一系列能夠包含多個值的屬性.在HTML5中移除了一些,卻增長更多.最多見的多值的屬性是
class (一個tag能夠有多個CSS的class). 還有一些屬性 rel , rev , accept-charset 
,headers , accesskey . 在Beautiful Soup中多值屬性的返回類型是list:
css_soup = BeautifulSoup('<p class="body strikeout"></p>') css_soup.p['class']                  # ["body", "strikeout"]

css_soup = BeautifulSoup('<p class="body"></p>') css_soup.p['class']                  # ["body"]
若是某個屬性看起來好像有多個值,但在任何版本的HTML定義中都沒有被定義爲多值屬性,
那麼Beautiful Soup會將這個屬性做爲字符串返回
 
  
id_soup = BeautifulSoup('<p id="my id"></p>') id_soup.p['id']                     # 'my id'

將tag轉換成字符串時,多值屬性會合併爲一個值

rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>') rel_soup.a['rel']              # ['index'] rel_soup.a['rel'] = ['index', 'contents'] print(rel_soup.p)              # <p>Back to the <a rel="index contents">homepage</a></p> 

若是轉換的文檔是XML格式,那麼tag中不包含多值屬性

xml_soup = BeautifulSoup('<p class="body strikeout"></p>', 'xml') xml_soup.p['class']             # u'body strikeout'

2、NavigableString

字符串常被包含在tag內.Beautiful Soup用 NavigableString 類來包裝tag中的字符串:

tag.string          # u'Extremely bold' type(tag.string)      # <class 'bs4.element.NavigableString'>

  一個 NavigableString 字符串與Python中的Unicode字符串相同,而且還支持包含在 

遍歷文檔樹和 搜索文檔樹 中的一些特性. 

unicode_string = encode('utf-8') unicode_string            # u'Extremely bold' type(unicode_string)         # <type 'unicode'>

tag中包含的字符串不能編輯,可是能夠被替換成其它的字符串,用 replace_with() 方法:

tag.string.replace_with("No longer bold") tag                  # <blockquote>No longer bold</blockquote>

3、BeautifulSoup
BeautifulSoup 對象表示的是一個文檔的所有內容.大部分時候,
能夠把它看成 Tag 對象,它支持 遍歷文檔樹 和 搜索文檔樹 中描述的大部分的方法.

由於 BeautifulSoup 對象並非真正的HTML或XML的tag,因此它沒有name和attribute屬性.

但有時查看它的 .name 屬性是很方便的,因此 BeautifulSoup 對象包含了一個值爲 「[document]」 的特殊屬性 .name

 
  
soup.name        # u'[document]'

4、Comment

Tag , NavigableString , BeautifulSoup 幾乎覆蓋了html和xml中的全部內容,

可是還有一些特殊對象.容易讓人擔憂的內容是文檔的註釋部分:

 
  
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>" soup = BeautifulSoup(markup) comment = soup.b.string type(comment)        # <class 'bs4.element.Comment'> 
 
  

Comment 對象是一個特殊類型的 NavigableString 對象:

comment            # u'Hey, buddy. Want to buy a used parser'
 
  

可是當它出如今HTML文檔中時, Comment 對象會使用特殊的格式輸出:

 
  
print(soup.b.prettify()) # <b> # <!--Hey, buddy. Want to buy a used parser?--> # </b>
 
  

Beautiful Soup中定義的其它類型均可能會出如今XML的文檔中: CData , ProcessingInstructionDeclaration , 

Doctype .與 Comment 對象相似,這些類都是 NavigableString 的子類,只是添加了一些額外的方法的字符串獨享.

下面是用CDATA來替代註釋的例子:

 
  
from bs4 import CData cdata = CData("A CDATA block") comment.replace_with(cdata) print(soup.b.prettify()) # <b> # <![CDATA[A CDATA block]]> # </b>
 
1、遍歷文檔樹
相關文章
相關標籤/搜索