2014-10-07 46 views
0

問題刪除與beautifulsoup和Python

我試圖消除像我的HTML文件,該文件是由BeautifulSoup下載<h2><div class=...>風格標籤某些標記。我想保留標籤包含的內容(如文本) 但是,這似乎並不奏效。

我曾嘗試

for url in urls: 
    response = requests.get(url, headers=headers) 
    soup = BeautifulSoup(response.content, 'html.parser') 
    table = soup.find("div", {"class": "product_specifications bottom_l js_readmore_content"}) 
    print "<hr style='border-width:5px;'>" 
    for style in table.find_all('style'): 
     if 'style' in style.attrs: 
      del style.attrs['style'] 
    print table 

的url我試圖與工作

Python HTML parsing with beautiful soup and filtering stop words

Remove class attribute from HTML using Python and lxml

BeautifulSoup Tag Removal

+0

你還沒有解釋什麼不與當前解決方案的工作。 – Veedrac 2014-10-07 10:17:43

+0

它的stil風格是其原始頁面。 – user3671459 2014-10-07 11:26:05

回答

2

您可以使用decompose()http://www.crummy.com/software/BeautifulSoup/bs4/doc/#decompose

如果你想清除不僅僅是文本或保存從樹中移除元素,使用clearextract(描述略高於分解)。

+0

我仍然需要保持其內容。我想刪除的唯一的事情就是標籤本身。因爲它的樣式我的文件,我不想 – user3671459 2014-10-07 11:25:47

+0

所以請解釋它的問題,而不是我的意見 – 2014-10-07 14:08:51

0

您正在尋找unwrap()。

your_soup.tag.unwrap()