# coding:utf-8
from bs4 import BeautifulSoup
import bs4
html_str = """
<html><head><title>The Dormouse's story</title></head>
<body>
<P class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names
were
<a href ="http://example.corn/elsie" class="sister" id="linkl" ><!-- Elsie --></a>,
<a href= "http://example.corn/lacie" class="sister" id="link2" >< ! -- Lacie -->< /a> and
<a href= "http://example.corn/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well. </p>
<p class = "story"> ... </p>
"""
soup = BeautifulSoup(html_str, 'lxml', from_encoding='utf-8')
#文檔被轉換成Unicode,並且HTML的實例都被轉化成Unicode編碼。打印soup對象的內容,格式化輸出
print(soup.prettify())
#對象種類:Tag、NavigableString、BeautifulSoup和Comment
#***********************************************************************Tag*******
#Tag:本質上就是標記。比如title以及a標記及其裏面的內容
#分別抽取title、a和p,需要注意的是當有多個同類標記時,僅僅提取第一個標記及其裏面的內容
print(soup.title) # <title>The Dormouse's story</title>
print(soup.a) #<a class="sister" href="http://example.corn/elsie" id="linkl">< ! -- Elsie --></a>
print(soup.p) #<p class="title"><b>The Dormouse's story</b></p>
#Tag中存在的兩個重要的屬性name和attributes
print(soup.name) #soup比較特殊,它的name爲[document]
print(soup.title.name) # title
#還可以更改name,更改name之後在該soup對象中永久更改
soup.title.name = "mytitle"
print(soup.title) #None
print(soup.mytitle) #<mytitle>The Dormouse's story</mytitle>
#獲取屬性值操作
print(soup.p['class']) #['title']
print(soup.p.get('class')) #['title']
#直接獲取屬性
print(soup.p.attrs) #{'class': ['title']}
#****************************NavigableString********************
#我們已經得到了標記的內容, 要想獲取標記內部的文字怎麼辦呢?
#Beautiful Soup用NavigableString類來包裝Tag中的字符串,一個NavigableString字符串與Python中的Unicode字符串相同
print(soup.p.string)
print(type(soup.p.string))
#The Dormouse's story
#<class 'bs4.element.NavigableString'>
#**********************BeautifulSoup****************
#BeautifulSoup對象表示的是一個文檔的全部內容。大部分時候可以將其當作Tag對象,
#是一個特殊的Tag,因爲BeautifulSoup對象並不是真正的HTML和XML的標記,所以其沒有name和atribute屬性。但是
#爲了將BS對象標準化爲Tag對象,實現接口的統一,我們依然可以分別獲取它的nameheattribute屬性
print(type(soup.name))
print(soup.name)
print(soup.attrs)
#<type 'unicode'>
#[document]
#{}
#*************Comment**************
#a裏面的內容實際是註釋,但是輸出的內容將註釋去除了
print(soup.a.string) #Elsie
#查看其類型可以發現其是一個Comment類型
print(type(soup.a.string))#<class 'bs4.element.Comment'>
#可以通過以下語句判斷是否是Comment
if type(soup.a.string) == bs4.element.Comment:
print(soup.a.string)
基於《Python爬蟲開發與項目實戰》