BeautifulSoup的高级应用 之 contents children descendants string strings stripped_strings
繼上一節。BeautifulSoup的高級應用 之 find findAll,這一節,主要解說BeautifulSoup有關的其它幾個重要應用函數。
本篇中,所使用的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 屬性能夠將 tag的子節點以列表的形式輸出。
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對象本身一定會包括子節點 ,也就是說 標簽也是 BeautifulSoup 對象的子節點 :
len(soup.contents) # 1 soup.contents[0].name # u'html'字符串沒有.contents 屬性 ,由于字符串沒有子節點 :
text = title_tag.contents[0] text.contents # AttributeError: 'NavigableString' object has no attribute 'contents'通過 tagtagtag的 .children 生成器 ,能夠對 tagtagtag的子節點進行循環 :
for child in title_tag.children: print(child) # The Dormouse's story.descendants:
.contents和 .children 屬性僅包括 tagtagtag的直接子節點 .比如 ,標簽僅僅有一個直接子節點
可是 標簽也包括一個子節點 :字符串 字符串 “The Dormouse’s story”, 這樣的情況下字符串 “The Dormouse’s story” 也屬于 標簽的子孫節點 .descendants 屬性能夠對全部 tagtagtag的子孫節 點進行遞歸循環
for child in head_tag.descendants: print(child) # <title>The Dormouse's story</title> # The Dormouse's story標簽僅僅有一個子節點 ,可是有 2個子孫節點 :節點和 的子 節點 , BeautifulSoup 有一個直接子節點 (節點 ), 卻有非常多子孫節點 :
len(list(soup.children)) #這里是html的children子節點 # 1 len(list(soup.descendants)) #這里是html的descendants子孫節點 多個 # 25.string:
假設 tagtagtag僅僅有一個 NavigableString 類型子節點 ,那么這個 tag能夠使用.string 得到子節點 :
假設一個 tag僅有一個子節點 ,那么這個 tag也能夠使用 .string 方法 ,輸出結果與當前唯一子 節點的 .string 結果同樣 .
假設 tag包括了多個子節點,tag就無法確定 .string.string.string .string.方法應該調用哪個子節點的內 , .string 的輸出結果是 None。
strings 和 stripped_strings:
假設 tag中包括多個字符串 ,能夠使用.strings 來循環獲取 :
輸出的字符串中 可能包括了非常多空格或行 ,使用 .stripped_strings 能夠去除多余空白內容 :
for string in soup.stripped_strings: print(repr(string))下一篇我們解說父節點。兄弟節點,回退和前進。
總結
以上是生活随笔為你收集整理的BeautifulSoup的高级应用 之 contents children descendants string strings stripped_strings的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot . 配置jpa使用
- 下一篇: 数据库副本的自动种子设定(自增长)