bs4: “soup.title.string” doesn't work on IDLE

2019-04-01 10:19发布

问题:

Mac OS X 10.9 Python 2.7 IDLE BeautifulSoup 4 installed (successfully)

I followed BS4 documentation and was practicing some of the functions on IDLE. The following code works and was able to print out 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

Print result:

<title>The Dormouse's story</title>
title

But as I moved on and tried to print soup.title.string in the next line:

print soup.title.string

It returned:

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

AND THEN, I tried to run the same code on Terminal:

Python [filename].py

It worked!

<title>The Dormouse's story</title>
title
The Dormouse's story

Can someone explained why the code didn't work on IDLE but Terminal? Thank you!

回答1:

This was a known bug, reported on the Python issue tracker as issue #23583: IDLE: printing unicode subclasses broken (again).

This was fixed a few months ago, so beginning with version 2.7.10 this should no longer happen. Try updating your Python!