Python Beautiful Soup .content属性

时间:2013-10-26 03:13:53

标签: python beautifulsoup

BeautifulSoup的内容有什么作用?我正在通过crummy.com's教程,我并不真正理解.content的作用。我看过论坛,我没有看到任何答案。看下面的代码......

from BeautifulSoup import BeautifulSoup
import re



doc = ['<html><head><title>Page title</title></head>',
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
        '<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
        '</html>']

soup = BeautifulSoup(''.join(doc))
print soup.contents[0].contents[0].contents[0].contents[0].name

我希望代码的最后一行打印出'body'而不是......

  File "pe_ratio.py", line 29, in <module>
    print soup.contents[0].contents[0].contents[0].contents[0].name
  File "C:\Python27\lib\BeautifulSoup.py", line 473, in __getattr__
    raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
AttributeError: 'NavigableString' object has no attribute 'name'

.content只关注html,head和title吗?如果,为什么会这样?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

它只是给你里面标签。让我用一个例子来证明:

html_doc = """
<html><head><title>The Dormouse's story</title></head>

<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
head = soup.head

print head.contents

上面的代码为我提供了一个列表[<title>The Dormouse's story</title>],因为那里的 head标记。因此,调用[0]将为您提供列表中的第一项。

您收到错误的原因是soup.contents[0].contents[0].contents[0].contents[0]返回没有其他标签的内容(因此没有属性)。它会从您的代码返回Page Title,因为第一个contents[0]为您提供HTML标记,第二个为您提供head标记。第三个引出title标记,第四个引用实际内容。因此,当您在其上调用name时,它没有标记可供您使用。

如果您想要打印正文,可以执行以下操作:

soup = BeautifulSoup(''.join(doc))
print soup.body

如果您希望body仅使用contents,请使用以下内容:

soup = BeautifulSoup(''.join(doc))
print soup.contents[0].contents[1].name

您不会使用[0]作为索引,因为bodyhead之后的第二个元素。

相关问题