Python Beautiful Soup .content属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python Beautiful Soup .content属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2230字,纯文字阅读大概需要4分钟。
内容图文
![Python Beautiful Soup .content属性](/upload/InfoBanner/zyjiaocheng/786/b55140482b08491d89f7a2415bca301a.jpg)
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吗?如果,那为什么呢?
我在这里先向您的帮助表示感谢.
解决方法:
它只是给你标签内的什么.让我举个例子来证明:
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的故事< / title>],因为它在head标签内.所以调用[0]会给你列表中的第一项.
你得到错误的原因是因为soup.contents [0] .contents [0] .contents [0] .contents [0]返回没有其他标签的东西(因此没有属性).它返回代码中的Page Title,因为第一个内容[0]为您提供HTML标记,第二个内容为您提供head标记.第三个引出标题标签,第四个引出实际内容.因此,当您在其上调用名称时,它没有标记可以提供给您.
如果要打印正文,可以执行以下操作:
soup = BeautifulSoup(''.join(doc))
print soup.body
如果您只想使用内容,请使用以下内容:
soup = BeautifulSoup(''.join(doc))
print soup.contents[0].contents[1].name
你不会使用[0]作为索引,因为body是head之后的第二个元素.
内容总结
以上是互联网集市为您收集整理的Python Beautiful Soup .content属性全部内容,希望文章能够帮你解决Python Beautiful Soup .content属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。