2016-03-23 6 views
2

次のように私は、HTML文書を持っている:HTML文書をCutting/SlicingしてBeautifulSoupで分割しますか?

<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 to pull out of the document.</p> 
<h2> References </h2> 
<p>Html I do not want...</p> 

私は二H2タグでドキュメントをスライスしたい、記事からの参照を必要としません。

もちろん、私はそうのようなH2タグのリストを見つけることができます。

soup = BeautifulSoup(html) 
soupset = soup.find_all('h2') 
soupset[1] #this would get the h2 heading 'References' but not what comes before it 

私はH2タグのリストを取得する必要はありませんが、私は右の二H2タグでドキュメントをスライスしたいと上記の内容を新しい変数に保存してください。基本的に私がしたい所望の出力は次のようになります。

<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 to pull out of the document.</p> 

この「スライス」HTML文書の/切断を行う代わりに、単純にタグを見つけ、タグ自体をoutputing aboout行くための最善の方法は何ですか?

答えて

1

することはできremove/extract「参考文献」要素のすべての兄弟要素と要素自体:

import re 
from bs4 import BeautifulSoup 

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 to pull out of the document.</p> 
    <h2> References </h2> 
    <p>Html I do not want...</p> 
</div> 
""" 
soup = BeautifulSoup(data, "lxml") 

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

print(soup) 

プリント:

<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 to pull out of the document.</p> 
</div> 
+0

これはうまくいくと思います!大変感謝しています。非常にきれいな。私が明確に理解したことを確認するために、h2タグ内のすべてのHTMLを削除するにはelm.extract()を実行するループが必要ですか?それから、end references.extract()は、 'References' h2タグをすべて削除した後、単純に削除します。 – EazyC

+1

@ EazyC私はそれが助けてくれることを願っています。ループの中でReferences要素の次のすべての兄弟を削除してから、References要素自体を削除します。 – alecxe

+0

これはちょうど感謝したようです! – EazyC

0

あなたは、文字列にh2の場所を見つけることができ、その後、部分文字列を見つける:

last_h2_tag = str(soup.find_all("h2")[-1]) 
html[:html.rfind(last_h2_tag) + len(last_h2_tag)] 
関連する問題