body = body.encode('ascii','ignore')AttributeError:'list'对象没有属性'encode'

时间:2013-09-07 11:36:11

标签: python python-2.7 encoding character-encoding beautifulsoup

为什么以下代码会给我一条错误消息:AttributeError: 'list' object has no attribute 'encode'

import urllib2                  
from BeautifulSoup import BeautifulSoup

opener = urllib2.build_opener()         
opener.addheaders = [('user-agent', 'Mozilla/5.0')]

url = ('http://en.wikipedia.org/wiki/Pink_Floyd')

thisurl= opener.open(url).read()

soup = BeautifulSoup(thisurl)      
title = soup.title.text

body = soup.findAll('p')       
body = body.encode('ascii','ignore')

for i in body:         
    print i.text

1 个答案:

答案 0 :(得分:1)

您正在尝试encode列表(findAll的结果是出现的列表)。你需要做的是遍历列表,获取你想要的文本并对其进行编码。

body = soup.findAll('p')

for i in body:
    print i.text.encode('ascii','ignore')