如何只返回HTML代码段中的文本?

时间:2013-06-20 01:28:48

标签: python html beautifulsoup

我有一个HTML代码段,如下所示:

<pre>zdfsfsf<br/>adfadfadf
adfadfasdfadfad  adfadf adf 
Mill Valley, CA 94941
122-2323-24124
Email: adfadfadf<br/><i>sfsfsfsf</i></pre>
<br/>

我想剥离所有标签,只是拥有文字。

内容应如下所示:

zdfsfsf adfadfadf
adfadfasdfadfad  adfadf adf 
Mill Valley, CA 94941
122-2323-24124
Email: adfadfadf sfsfsfsf

我正在寻找类似的东西:

cells = row.find_all('td')
for c in cells:
    c.STRIP_HTML_TAGS()?????? <--WHAT IS THIS FUNCTION?

1 个答案:

答案 0 :(得分:3)

您正在寻找get_text()

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("""<pre>zdfsfsf<br/>adfadfadf
... adfadfasdfadfad  adfadf adf 
... Mill Valley, CA 94941
... 122-2323-24124
... Email: adfadfadf<br/><i>sfsfsfsf</i></pre>
... <br/>""")
>>> print(soup.get_text())
zdfsfsfadfadfadf
adfadfasdfadfad  adfadf adf 
Mill Valley, CA 94941
122-2323-24124
Email: adfadfadfsfsfsfsf
>>>