1. 程式人生 > >BeautifulSoup的高級應用 之 contents children descendants string strings stripped_strings

BeautifulSoup的高級應用 之 contents children descendants string strings stripped_strings

sheet att sso track win csdn 調用 rod pan

繼上一節。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的直接子節點 .比如 ,標簽僅僅有一個直接子節點

head_tag.contents 
# [<title>The Dormouse‘s story</title>]

可是 標簽也包括一個子節點 :字符串 字符串 “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