我想刮掉倾斜的绳子"睡鼠的故事"在HTML中,使用beautifulsoup工具。
#!/usr/bin/python
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
html_doc = """
<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_doc)
print soup.title.string
我使用Python2.7.9 IDE,错误描述为
Traceback (most recent call last):
File "C:/Python27/Scripts/test.py", line 23, in <module>
print soup.title.string
File "C:\Python27\lib\idlelib\PyShell.py", line 1353, in write
s = unicode.__getslice__(s, None, None)
TypeError: an integer is required
如果我需要更改变量的类型,我该如何解决这个问题?
答案 0 :(得分:1)
使用运行模块命令运行脚本时,这是IDLE中的错误;解决方法是在对象上使用unicode()
:
print unicode(soup.title.string)
问题是由issue 19481的错误修复引起的;我怀疑unicode.__getslice__
方法已被清除和/或从不支持使用None
索引,至少在Python 2中。
我为此问题打开了new bug on IDLE。
答案 1 :(得分:0)
我认为这是IDE中的一个错误,当我使用它时,没有错误。
<<ret = urllib2.urlopen(url).read()
<<soup = BeautifulSoup(ret)
<<print soup.title.string
<<About Me