2013-04-25 50 views

答えて

1

を行うための方法です!このラインとその

ような単純なあなたは一緒に現在の要素内のすべてのテキスト部分

''.join(htmlelement.find(text=True)) 
2

に参加しているあなたは、BS4中で分解の方法を使用することができます。

soup = bs4.BeautifulSoup('<body><a href="http://example.com/">I linked to <i>example.com</i></a></body>') 

for a in soup.find('a').children: 
    if isinstance(a,bs4.element.Tag): 
     a.decompose() 

print soup 

Out: <html><body><a href="http://example.com/">I linked to </a></body></html> 
46

が、それはのpython3

from bs4 import BeautifulSoup 

soup = BeautifulSoup(html) 
text = soup.get_text() 
print(text) 
+4

それはさ'getText()'の代わりに 'get_text()'を使うほうがいいです。 – SparkAndShine

+1

なぜですか?それは事実かもしれませんが、理由を理解することは役に立ちます。 –

+11

getText()はbs3構文であり、pep8に準拠していません。おそらく廃止予定です。 –

6

使用get_text()にでも簡単です、それは文書内のすべてのテキストを返すか、下に単一のUnicode文字列としてのタグ。例えば

、次のテキストからすべての異なるスクリプトタグを削除します。

<td><a href="http://www.irit.fr/SC">Signal et Communication</a> 
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a> 
</td> 

期待される結果は次のとおりです。ここで

Signal et Communication 
Ingénierie Réseaux et Télécommunications 

は、ソースコードである:

#!/usr/bin/env python3 
from bs4 import BeautifulSoup 

text = ''' 
<td><a href="http://www.irit.fr/SC">Signal et Communication</a> 
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a> 
</td> 
''' 
soup = BeautifulSoup(text) 

print(soup.get_text()) 
関連する問題