【发布时间】:2014-06-18 22:23:15
【问题描述】:
Mac OS X 10.9 Python 2.7 空闲 BeautifulSoup 4 已安装(成功)
我关注了BS4 documentation,正在在IDLE上练习一些功能。以下代码有效,并且能够打印出 title 和 title.name。
from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<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>
"""
soup = BeautifulSoup(html)
print soup.title
print soup.title.name
打印结果:
<title>The Dormouse's story</title>
title
但是当我继续前进并尝试在下一行打印 soup.title.string 时:
print soup.title.string
它返回:
Traceback (most recent call last):
File "/Users/yumiyang/Documents/python-folder/bsoup_test.py", line 24, in <module>
print soup.title.string
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/idlelib/PyShell.py", line 1344, in write
s = unicode.__getslice__(s, None, None)
TypeError: an integer is required
然后,我尝试在终端上运行相同的代码:
Python [文件名].py
成功了!
<title>The Dormouse's story</title>
title
The Dormouse's story
有人可以解释为什么代码不能在 IDLE 上运行,而是在终端上运行吗?谢谢!
【问题讨论】:
-
已修改 - unicode(soup.title.string) 适用于 IDLE。
标签: string terminal beautifulsoup osx-mavericks python-idle