使用Python 2.7从HTML中提取文本

时间:2014-01-16 20:34:07

标签: python-2.7 beautifulsoup

我的代码如下:

s = """<P><A>This is the topic</A>
This is the text</P>
<P>&nbsp;</P>
<P><A>Another Topic</A>:
Another Text </P>"""
for s in soup.findAll('a'):
   print s.text

输出是:

This is the topic
Another Topic

我想要“这是文本”和“另一个文本”。但不知怎的,我无法使用此代码。条件是我必须使用for循环。因此,如果有人知道如何提取所需的文本,那将会有很大的帮助。

1 个答案:

答案 0 :(得分:1)

尝试获取段落标记内的文字:

s = '<P><A>This is the topic</A>This is the text</P><P>&nbsp;</P><P><A>Another Topic</A>:Another Text </P>'

汤= BeautifulSoup(s)

for s in soup.findAll('p'):
    #if the contents[1] have the NavigableString
    if len(s.contents) > 1:
      print s.contents[1] + '\n'

输出结果为:

This is the text

:Another Text