2017-01-13 55 views
1

我試圖用Beautifuloup來提取html標籤並刪除文本。例如採取這個網站:美麗的湯萃取物標籤刪除文本

html_page = """ 
<html> 
<body> 
<table> 
<tr class=tb1><td>Lorem Ipsum dolor Sit amet</td></tr> 
<tr class=tb1><td>Consectetuer adipiscing elit</td></tr> 
<tr><td>Aliquam Tincidunt mauris eu Risus</td></tr> 
<tr><td>Vestibulum Auctor Dapibus neque</td></tr> 
</table> 
</body> 
</html> 
""" 

期望的結果是:

<html> 
<body> 
<table> 
<tr><td></td></tr> 
<tr><td></td></tr> 
<tr><td></td></tr> 
<tr><td></td></tr> 
</table> 
</body> 
</html> 

這裏是我到目前爲止有:

def get_tags(soup): 
    copy_soup = soup 
    for tag in copy_soup.findAll(True): 
     tag.attrs = {} # removes attributes of a tag 
     tag.string = '' 

    return copy_soup 

print get_tags(soup) 

使用tag.attrs = {}工程刪除所有標籤屬性。但是,當我嘗試使用tag.string或tag.clear()我只剩下<html></html>。我知道可能發生的情況是在第一次使用tag.stringtag.clear()時刪除了html標記中的所有內容。

我不確定如何解決此問題。也許先遞歸地從孩子中刪除文本?還是有更簡單的方法我錯過了?

回答

1

你不能簡單的復位.string爲空字符串,因爲如果元素與文本一個孩子,就像在你的榜樣tr元素,你會無意中刪除從樹中td元素。

您不能使用.clear(),因爲它也遞歸地刪除所有子節點。

我不記得一個內置的方式來獲得HTML樹結構沒有數據BeautifulSoup - 我會用下面的辦法:

for elm in soup.find_all(): 
    if not elm.find(recursive=False): # if not children 
     elm.string = '' 
    elm.attrs = {} 

在這裏,我們重置.string只有在有沒有孩子。

演示:

>>> from bs4 import BeautifulSoup 
>>> 
>>> html_page = """ 
... <html> 
... <body> 
... <table> 
... <tr class=tb1><td>Lorem Ipsum dolor Sit amet</td></tr> 
... <tr class=tb1><td>Consectetuer adipiscing elit</td></tr> 
... <tr><td>Aliquam Tincidunt mauris eu Risus</td></tr> 
... <tr><td>Vestibulum Auctor Dapibus neque</td></tr> 
... </table> 
... </body> 
... </html> 
... """ 
>>> 
>>> soup = BeautifulSoup(html_page, "html.parser") 
>>> for elm in soup.find_all(): 
...  if not elm.find(recursive=False): 
...   elm.string = '' 
...  elm.attrs = {} 
... 
>>> print(soup.prettify()) 
<html> 
<body> 
    <table> 
    <tr> 
    <td> 
    </td> 
    </tr> 
    <tr> 
    <td> 
    </td> 
    </tr> 
    <tr> 
    <td> 
    </td> 
    </tr> 
    <tr> 
    <td> 
    </td> 
    </tr> 
    </table> 
</body> 
</html> 
+0

啊,謝謝你的解釋,尤其是對準確描述爲什麼我原來的做法是有缺陷的。 –

+0

@ hannahbanana2.0高興地幫助,我試圖看看是否有一個更美麗的方式來解決你的問題......看着'lxml'和'lxml.objectify' .. – alecxe

+0

@ hannahbanana2.0 btw,這裏是一個[很相關的話題](http://stackoverflow.com/questions/24640959/get-a-structure-of-html-code)與另一種方法 - 可能比我們在這裏做的更簡單。 – alecxe