2017-04-05 19 views
0

我讀過.contents返回標籤的直接子元素,如果我們想要迭代這些子元素,我們應該使用.children。但我已經嘗試了他們,並得到了相同的輸出。.contents和.children之間的差異

html_doc = """ 
<html><head><title>The Dormouse's story</title></head> 
<body> 
<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></body></html> 
""" 
soup = BeautifulSoup(html_doc, "html.parser") 
title_tag = soup.title 

for child in title_tag.children: 
    print(child) 
for child in title_tag.contents: 
    print(child) 
+0

我得到了'NameError:name'title_tag'未定義'。如何使這個工作的例子? – tdelaney

+0

對不起。好,完成! – Hamza

回答

0

該文檔比這更微妙一點。它說

Instead of getting them as a list, you can iterate over a tag’s children using the .children generator

但是你可以列出直接在迭代for循環,你可以通過調用iter()獲得一個迭代器,因此它似乎kindof毫無意義,甚至有.children財產。仔細看,這裏是如何實現children

#Generator methods 
@property 
def children(self): 
    # return iter() to make the purpose of the method clear 
    return iter(self.contents) # XXX This seems to be untested. 

是的,這是完全沒有意義的。這兩段代碼是相同的,只不過for child in title_tag.contents獲得列表的迭代器,而for child in title_tag.children使用迭代器。

0

考慮到你在談論BeautifulSoup(你應該給我們一些背景內容!)...

至於說here,主要的區別在於.contents你會得到一個列表,而與.children你會得到一個發電機。

它似乎沒有任何區別,因爲您可以迭代它們兩個,但是當您使用大量數據時,應該始終更喜歡使用生成器來節省計算機的內存。

想象一下:你有一個10K的文本文件,你需要在每一行工作。當使用一個列表(例如:with open('t.txt') as f: lines = f.readlines())時,你會用一些你不會馬上工作的東西來填充你的大部分內存,只是在那裏花費空間(更不用說依靠你的環境,你可能沒有內存不夠......)在使用發電機的時候,你會根據需要得到一條線,但是沒有內存消耗......

相關問題