2016-07-17 29 views
1

私はBeautifulSoupを使ってタグなしでテキストを取得しようとしています。私は、.contentsの.text、.find(テキスト=真)、およびを.next_sibling を.string を使用してみました、そして、彼らは以下のとおりです。BeautifulSoupを使ってタグなしでテキストを取得する

編集 Nvmd私はちょうどは私にとって作品を.next_siblingことに気づきました。とにかくこの質問は、同様のケースを扱うメモ収集メソッドです。

import bs4 as BeautifulSoup 
s = """ 
<p> 
    <a> 
     Something I can fetch but don't want 
    </a> 
    I want to fetch this line. 
    <a> 
     Something else I can fetch but don't want 
    </a> 
</p> 
""" 

p = BeautifulSoup(s, 'html.parser') 
print p.contents    
    # [u'\n', <p> 
    # <a> 
    #  Something 
    # </a> 
    #  I want to fetch this line. 
    # <a> 
    #  Something else 
    # </a> 
    # </p>, u'\n'] 

print p.next_sibling.string 
    # I want to fetch this line. 
print p.string    
    # None 
print p.text   
    # all the texts, including those I can get but don't want. 
print p.find(text=True) 
    # Returns an empty line of type bs4.element.NavigableString 
print p.find(text=True)[0] 
    # Returns an empty line of type unicode 

手動で私が取得したい行を取得するために、文字列sを解析するよりも簡単な方法がある場合、私は思ったんだけど?

答えて

2

これを試してください。それでもまだ荒いですが、少なくとも文字列を手動で解析する必要はありません。

#get all non-empty strings from the backend. 
texts = [str.strip(x) for x in p.strings if str.strip(x) != ''] 

#get strings only with tags 
unwanted_text = [str.strip(x.text) for x in p.find_all()] 

#take the difference 
set(texts).difference(unwanted_text) 

この利回り:

In [87]: set(texts).difference(unwanted_text) 
Out[87]: {'I want to fetch this line.'} 
+0

これは本当に天才です....... –

関連する問題