【问题标题】:Extracting Text from HTML Using Python 2.7使用 Python 2.7 从 HTML 中提取文本
【发布时间】:2014-01-17 05:10:04
【问题描述】:

我的代码如下:

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 循环。因此,如果有人知道如何提取所需的文本,那将是非常有帮助的。

【问题讨论】:

  • 谢谢大家。我尝试在 soup.findAll('a') 中使用 - for s: print s.parent.text ...它起作用了
  • 使用 s.parent.text 我获得了所有段落的所有文本,如下所示:This is the topicThis is the text

标签: python-2.7 beautifulsoup


【解决方案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 

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多