2016-05-15 4 views
1

私は後で、美しいsoup tag.extract()関数で抽出するのではなく、HTMLページの部分をコメントアウトしようとしています。例:美味しいスープ:タグを抽出するのではなくコメントにするのに最適な方法は?

<h1> Name of Article </h2> 
<p>First Paragraph I want</p> 
<p>More Html I'm interested in</p> 
<h2> Subheading in the article I also want </h2> 
<p>Even more Html i want blah blah blah</p> 
<h2> References </h2> 
<p>Html I want commented out</p> 

参考文献の見出しがコメントアウトされていることをすべて欲しがります。もちろん、私はとても美しいスープの抽出機能を使用してのようなものを抽出することができます。

soup = BeautifulSoup(data, "lxml") 

references = soup.find("h2", text=re.compile("References")) 
for elm in references.find_next_siblings(): 
    elm.extract() 
references.extract() 

は私も美しいスープは、あなたのように使用することができ、コメント作成機能を可能にすることを知っているので

from bs4 import Comment 

commented_tag = Comment(chunk_of_html_parsed_somewhere_else) 
soup.append(commented_tag) 

これは非常にunpythonicようで、特にタグが太いhtmlツリーの真ん中にある場合は、HTMLタグを直接特定のタグの外側にカプセル化するのは面倒な方法です。あなたは単にbeautifulsoupでタグを見つけて、ちょうどその前と後に<!-- -->と置くのが簡単な方法はありませんか?前もって感謝します。

答えて

1

問題を正しく理解しているとすれば、replace_with()を使用して、タグをCommentインスタンスに置き換えることができます。これはおそらく、既存のタグをコメントする最も簡単な方法です:

import re 

from bs4 import BeautifulSoup, Comment 

data = """ 
<div> 
    <h1> Name of Article </h2> 
    <p>First Paragraph I want</p> 
    <p>More Html I'm interested in</p> 
    <h2> Subheading in the article I also want </h2> 
    <p>Even more Html i want blah blah blah</p> 
    <h2> References </h2> 
    <p>Html I want commented out</p> 
</div>""" 

soup = BeautifulSoup(data, "lxml") 
elm = soup.find("h2", text=re.compile("References")) 
elm.replace_with(Comment(str(elm))) 

print(soup.prettify()) 

プリント:

<html> 
<body> 
    <div> 
    <h1> 
    Name of Article 
    </h1> 
    <p> 
    First Paragraph I want 
    </p> 
    <p> 
    More Html I'm interested in 
    </p> 
    <h2> 
    Subheading in the article I also want 
    </h2> 
    <p> 
    Even more Html i want blah blah blah 
    </p> 
    <!--<h2> References </h2>--> 
    <p> 
    Html I want commented out 
    </p> 
    </div> 
</body> 
</html> 
関連する問題