1. 程式人生 > >Python爬蟲包 BeautifulSoup 學習(七) children等應用

Python爬蟲包 BeautifulSoup 學習(七) children等應用

所使用的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 
print head_tag 
head_tag.contents 
title_tag = head_tag.contents[0] 
print title_tag 
print title_tag.contents 

# <head><title>The Dormouse's story</title></head>
# [<title>The Dormouse's story</title>] # <title>The Dormouse's story</title> # [u'The Dormouse's story']

BeautifulSoup物件本身一定會包含子節點 ,也就是說 標籤也是 BeautifulSoup 物件的子節點 :

len(soup.contents) 
# 1 
soup.contents[0].name 
# u'html'

字串沒有.contents 屬性 ,因為字串沒有子節點 :

text = title_tag.contents[0] 
print text.contents 
# AttributeError: 'NavigableString' object has no attribute 'contents'

通過 tag的 .children ,可以對 tag的直接子節點(父標籤的下一級)進行迴圈 :

for child in title_tag.children: 
    print(child)
# The Dormouse's story

.descendants

.contents和 .children 屬性僅包含 tag的直接子節點 。例如 :

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

而.descendants 屬性是父標籤下面所有級別的標籤,例如,tr標籤是table的子標籤,而tr、th、td等都是table的後代標籤,例如:

for child in head_tag.descendants: 
    print(child) 
# <title>The Dormouse's story</title>
# The Dormouse's story

標籤只有一個子節點,但是有 2個子孫節點。這個在之前講過,BeautifulSoup將HTML解析為一棵樹,以此來理解子節點與子孫節點就好理解了。

len(list(soup.children)) #這裡是html的children子節點
# 1 
len(list(soup.descendants)) #這裡是html的descendants子孫節點 多個
# 25

.string

如果tag只有一個NavigableString 型別子節點 ,那麼這個tag可以使用.string 得到子節點 :

title_tag.string 
# u'The Dormouse's story'

如果一個tag僅有一個子節點 ,那麼這個 tag也可以使用 .string 方法 ,輸出結果與當前唯一子節點的 .string 結果相同。

如果 tag包含了多個子節點,tag就無法確定 .string方法應該呼叫哪個子節點的內 , .string 的輸出結果是 None。

strings 和 stripped_strings

如果 tag中包含多個字串 ,可以使用.strings 來迴圈獲取 :

for string in soup.strings: 
    print(repr(string)) 

輸出的字串中 可能包含了很多空格或行 ,使用 .stripped_strings 可以去除多餘空白內容 :

for string in soup.stripped_strings: 
    print(repr(string))