1. 程式人生 > 程式設計 >Python爬蟲庫BeautifulSoup獲取物件(標籤)名,屬性,內容,註釋

Python爬蟲庫BeautifulSoup獲取物件(標籤)名,屬性,內容,註釋

一、Tag(標籤)物件

1.Tag物件與XML或HTML原生文件中的tag相同。

from bs4 import BeautifulSoup
soup = BeautifulSoup('<b class="boldest">Extremely bold','lxml')
tag = soup.b
type(tag)
bs4.element.Tag

2.Tag的Name屬性

每個tag都有自己的名字,通過.name來獲取

tag.name
'b'
tag.name = "blockquote" # 對原始文件進行修改
tag
<blockquote class="boldest">Extremely bold</blockquote>

3.Tag的Attributes屬性

獲取單個屬性

tag['class']
['boldest']

按字典的方式獲取全部屬性

tag.attrs
{'class': ['boldest']}

新增屬性

tag['class'] = 'verybold'
tag['id'] = 1
print(tag)
<blockquote class="verybold" id="1">Extremely bold</blockquote>

刪除屬性

del tag['class']
del tag['id']
tag
<blockquote>Extremely bold</blockquote>

4.Tag的多值屬性

多值屬性會返回一個列表

css_soup = BeautifulSoup('<p class="body strikeout"></p>','lxml')
print(css_soup.p['class'])
['body','strikeout']
rel_soup = BeautifulSoup('<p>Back to the <a rel="index">homepage</a></p>','lxml')
print(rel_soup.a['rel'])
rel_soup.a['rel'] = ['index','contents']
print(rel_soup.p)
['index']
<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']
'body strikeout'

二、可遍歷字串(NavigableString)

1.字串常被包含在tag內,使用NavigableString類來包裝tag中的字串

from bs4 import BeautifulSoup
soup = BeautifulSoup('<b class="boldest">Extremely bold','lxml')
tag = soup.b
print(tag.string)
print(type(tag.string))
Extremely bold
<class 'bs4.element.NavigableString'>

2.一個 NavigableString 字串與Python中的str字串相同,通過str() 方法可以直接將 NavigableString 物件轉換成str字串

unicode_string = str(tag.string)
print(unicode_string)
print(type(unicode_string))
Extremely bold
<class 'str'>

3.tag中包含的字串不能編輯,但是可以被替換成其它的字串,用 replace_with() 方法

tag.string.replace_with("No longer bold")
tag

<b class="boldest">No longer bold

三、BeautifulSoup物件 BeautifulSoup 物件表示的是一個文件的全部內容。

大部分時候,可以把它當作 Tag 物件,它支援 遍歷文件樹 和 搜尋文件樹 中描述的大部分的方法。

四、註釋與特殊字串(Comment)物件

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

Comment 物件是一個特殊型別的 NavigableString 物件

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

更多關於Python爬蟲庫BeautifulSoup的使用方法請檢視下面的相關連結