【发布时间】:2011-12-03 01:12:54
【问题描述】:
我一直在尝试使用 BeautifulSoup 在 Python 中编写一个小爬虫。 一切都很顺利,直到我尝试打印(或写入文件)包含在各种 HTML 元素中的字符串。我正在抓取的网站是:http://www.yellowpages.ca/search/si/1/Boots/Montreal+QC,其中包含各种法语字符。出于某种原因,当我尝试将内容打印到终端或文件中时,而不是像预期的那样解码字符串,我得到的是原始的 unicode 输出。 这是脚本:
from BeautifulSoup import BeautifulSoup as bs
import urllib as ul
##import re
base_url = 'http://www.yellowpages.ca'
data_file = open('yellow_file.txt', 'a')
data = ul.urlopen(base_url + '/locations/Quebec/Montreal/90014002.html').readlines()
bt = bs(str(data))
result = bt.findAll('div', 'ypgCategory')
bt = bs(str(result))
result = bt.findAll('a')
for tag in result:
link = base_url + tag['href']
##print str(link)
data = ul.urlopen(link).readlines()
#data = str(data).decode('latin-1')
bt = bs(str(data), convertEntities=bs.HTML_ENTITIES, fromEncoding='latin-1')
titles = bt.findAll('span', 'listingTitle')
phones = bt.findAll('a', 'phoneNumber')
entries = zip(titles, phones)
for title, phone in entries:
#print title.prettify(encoding='latin-1')
#data_file.write(title.text.decode('utf-8') + " " + phone.text.decode('utf-8') + "\n")
print title.text
data_file.close()
/************/
这个输出是:Projets Autochtones Du Qu\xc3\xa9bec
正如您所见,应该在魁北克使用的带有重音的 e 没有显示。我已经尝试了 SO 中提到的所有内容,调用 unicode(),将 fromEncoding 传递给汤,.decode('latin-1') 但我什么也没得到。
有什么想法吗?
【问题讨论】:
-
你想要输出是什么?
-
我希望解码操作将 Unicode 实体转换为可读字符,例如:“Québec”
标签: python unicode beautifulsoup decoding