BeautifulSoup的高级应用 之 contents children descendants string strings stripped_strings
繼上一節(jié)。BeautifulSoup的高級應(yīng)用 之 find findAll,這一節(jié),主要解說BeautifulSoup有關(guān)的其它幾個重要應(yīng)用函數(shù)。
本篇中,所使用的html為:
html_doc = """ <html> <head><title>The Dormouse's story</title></head> <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.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> </html>""".contents和.children
tag的 .contents 屬性能夠?qū)?tag的子節(jié)點以列表的形式輸出。
from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc) head_tag = soup.head head_tag # <head><title>The Dormouse's story</title></head> head_tag.contents [<title>The Dormouse's story</title>] title_tag = head_tag.contents[0] title_tag # <title>The Dormouse's story</title> title_tag.contents # [u'The Dormouse's story']BeautifulSoup對象本身一定會包括子節(jié)點 ,也就是說 標(biāo)簽也是 BeautifulSoup 對象的子節(jié)點 :
len(soup.contents) # 1 soup.contents[0].name # u'html'字符串沒有.contents 屬性 ,由于字符串沒有子節(jié)點 :
text = title_tag.contents[0] text.contents # AttributeError: 'NavigableString' object has no attribute 'contents'通過 tagtagtag的 .children 生成器 ,能夠?qū)?tagtagtag的子節(jié)點進(jìn)行循環(huán) :
for child in title_tag.children: print(child) # The Dormouse's story.descendants:
.contents和 .children 屬性僅包括 tagtagtag的直接子節(jié)點 .比如 ,標(biāo)簽僅僅有一個直接子節(jié)點
可是 標(biāo)簽也包括一個子節(jié)點 :字符串 字符串 “The Dormouse’s story”, 這樣的情況下字符串 “The Dormouse’s story” 也屬于 標(biāo)簽的子孫節(jié)點 .descendants 屬性能夠?qū)θ?tagtagtag的子孫節(jié) 點進(jìn)行遞歸循環(huán)
for child in head_tag.descendants: print(child) # <title>The Dormouse's story</title> # The Dormouse's story標(biāo)簽僅僅有一個子節(jié)點 ,可是有 2個子孫節(jié)點 :節(jié)點和 的子 節(jié)點 , BeautifulSoup 有一個直接子節(jié)點 (節(jié)點 ), 卻有非常多子孫節(jié)點 :
len(list(soup.children)) #這里是html的children子節(jié)點 # 1 len(list(soup.descendants)) #這里是html的descendants子孫節(jié)點 多個 # 25.string:
假設(shè) tagtagtag僅僅有一個 NavigableString 類型子節(jié)點 ,那么這個 tag能夠使用.string 得到子節(jié)點 :
假設(shè)一個 tag僅有一個子節(jié)點 ,那么這個 tag也能夠使用 .string 方法 ,輸出結(jié)果與當(dāng)前唯一子 節(jié)點的 .string 結(jié)果同樣 .
假設(shè) tag包括了多個子節(jié)點,tag就無法確定 .string.string.string .string.方法應(yīng)該調(diào)用哪個子節(jié)點的內(nèi) , .string 的輸出結(jié)果是 None。
strings 和 stripped_strings:
假設(shè) tag中包括多個字符串 ,能夠使用.strings 來循環(huán)獲取 :
輸出的字符串中 可能包括了非常多空格或行 ,使用 .stripped_strings 能夠去除多余空白內(nèi)容 :
for string in soup.stripped_strings: print(repr(string))下一篇我們解說父節(jié)點。兄弟節(jié)點,回退和前進(jìn)。
總結(jié)
以上是生活随笔為你收集整理的BeautifulSoup的高级应用 之 contents children descendants string strings stripped_strings的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot . 配置jpa使用
- 下一篇: 数据库副本的自动种子设定(自增长)