我的代码如下:
s = """<P><A>This is the topic</A>
This is the text</P>
<P> </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循环。因此,如果有人知道如何提取所需的文本,那将会有很大的帮助。
答案 0 :(得分:1)
尝试获取段落标记内的文字:
s = '<P><A>This is the topic</A>This is the text</P><P> </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