Python Beautiful Soup .content 属性

Rob*_*rch 5 python beautifulsoup

BeautifulSoup 的 .content 有什么作用?我正在学习 crummy.com 的教程,但我不太明白 .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
Run Code Online (Sandbox Code Playgroud)

我希望代码的最后一行打印出“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'
Run Code Online (Sandbox Code Playgroud)

.content 只关心 html、head 和 title 吗?如果,那是为什么?

我在这里先向您的帮助表示感谢。

Gam*_*iac 4

它只是为您提供标签内的内容。让我用一个例子来演示一下:

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
Run Code Online (Sandbox Code Playgroud)

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

您收到错误的原因是因为soup.contents[0].contents[0].contents[0].contents[0]返回的内容没有进一步的标签(因此没有属性)。它从您的代码返回Page Title,因为第一个contents[0]为您提供 HTML 标签,第二个为您提供标签head。第三个指向标签title,第四个提供实际内容。因此,当您调用 a 时name,它不会为您提供标签。

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

soup = BeautifulSoup(''.join(doc))
print soup.body
Run Code Online (Sandbox Code Playgroud)

如果您只想body使用contents,请使用以下内容:

soup = BeautifulSoup(''.join(doc))
print soup.contents[0].contents[1].name
Run Code Online (Sandbox Code Playgroud)

您不会将其用作[0]索引,因为body是 后的第二个元素head