Beautiful Soup 4 可遍歷的字符串

2021-05-20 17:38 更新

字符串常被包含在tag內(nèi).Beautiful Soup用 ?NavigableString? 類來包裝tag中的字符串:

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

一個 ?NavigableString? 字符串與Python中的Unicode字符串相同,并且還支持包含在 遍歷文檔樹 和 搜索文檔樹 中的一些特性. 通過 ?unicode()? 方法可以直接將 ?NavigableString? 對象轉換成Unicode字符串:

unicode_string = unicode(tag.string)
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>

?NavigableString? 對象支持 遍歷文檔樹 和 搜索文檔樹 中定義的大部分屬性, 并非全部.尤其是,一個字符串不能包含其它內(nèi)容(tag能夠包含字符串或是其它tag),字符串不支持 ?.contents? 或 ?.string? 屬性或 ?find()? 方法.

如果想在Beautiful Soup之外使用 ?NavigableString? 對象,需要調用 ?unicode()? 方法,將該對象轉換成普通的Unicode字符串,否則就算Beautiful Soup已方法已經(jīng)執(zhí)行結束,該對象的輸出也會帶有對象的引用地址.這樣會浪費內(nèi)存.


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號