2017-11-29 7 views
0

beautifulsoupを使用してタグに囲まれていないすべての最初の兄弟をすべてdiv.titleに選択するにはどうすればよいですか?以下の例ではタグに囲まれていないdivのすべての兄弟をbeautifulsoupで選択するにはどうすればよいですか?

、私が取得する必要があります:

[Text I care about which <b>can</b> have formatting..., Text I care about., Text I care about <span class='someclass'>which can be in a span</span>...]

<div class="level1"> 
    <div class="title"> 
     Title I do not care about 
    </div> 
    <div class="level2"> 
     <div class="title"> 
      Title I do not care about 
     </div> 
     Text I care about which <b>can</b> have formatting... 
    </div> 
    <div class="level2"> 
     <div class="title"> 
      Title I do not care about 
     </div> 
     <div class="level3"> 
      <div class="title"> 
       Title I do not care about 
      </div> 
      Text I care about. 
     </div> 
     <div class="level3"> 
      <div class="title"> 
       Title I do not care about 
      </div> 
      Text I care about <span class='someclass'>which can be in a span</span>... 
     </div> 
    </div> 
</div> 

私はいくつかの正規表現を使用して、特定の位置にテキストを変更する必要がありますのでご注意ください。したがって、私はあなたがあなたのfind_all結果項目から不要なコードを削除するBS4 extract()メソッドを使用することができますフォーマットタグ(bbrspanなど)

答えて

0

とテキスト全体を必要としています。例えば

:ここ

import bs4 
soup = bs4.BeautifulSoup(texthere) 
divs = soup.find_all("div", {"class":"level3"}) #Finds all divs 
for div in divs: 
    title = div.find("div", {"class":"title"}) #Finds the title within each div 
    title.extract() #Remove that title from the div 
    print(div.text) #Here I print the div.text, but you can repurpose this for whatever you need 

は、SOからの良い情報源です:Exclude unwanted tag on Beautifulsoup Python

はそれが役に立てば幸い!

+0

)残念ながら、クラスセレクタ 'level3'は、私が最初のテキストを見つけられないようにします。これを 'level2'で試してみると、' div.text'の 'div.level2'の全体が返されます。 また、テキストには' span'と 'br'という書式設定要素が取り除かれています。 私は探しているすべてのコンテンツを含む「スパン」を追加するために文書を変更しましたが、これは私がこのジェネレータにアクセスしたためにのみ機能します。 – nbeuchat

0
`from bs4 import BeautifulSoup; 

strn =""" 
<div class="level1"> 
    <div class="title"> 
     Title I do not care about 
    </div> 
    <div class="level2"> 
     <div class="title"> 
      Title I do not care about 
     </div> 
     Text I care about which <b>can</b> have formatting... 
    </div> 
    <div class="level2"> 
     <div class="title"> 
      Title I do not care about 
     </div> 
     <div class="level3"> 
      <div class="title"> 
       Title I do not care about 
      </div> 
      Text I care about. 
     </div> 
     <div class="level3"> 
      <div class="title"> 
       Title I do not care about 
      </div> 
      Text I care about <span class='someclass'>which can be in a span</span>... 
     </div> 
    </div> 
</div> """ 



soup = BeautifulSoup(strn, 'html.parser') 

the_divs= soup.find_all('div', class_='title') 
for the_div in the_divs: 
    for the_sibling in the_div.parent.contents: 
     if the_sibling.name != 'div': 
      print the_sibling.string 
` 

ここで 'the_sibling'変数で再生して、必要な文字列を作成します。 'str(the_sibling)'はラップされたタグでテキストを返します(あなたのものか、

関連する問題