为什么以下代码会给我一条错误消息: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
答案 0 :(得分:1)
您正在尝试encode
列表(findAll
的结果是出现的列表)。你需要做的是遍历列表,获取你想要的文本并对其进行编码。
body = soup.findAll('p')
for i in body:
print i.text.encode('ascii','ignore')