无法解码Python中BeautifulSoup的输出

时间:2011-12-03 01:12:54

标签: python unicode beautifulsoup decoding

我一直在尝试使用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(),从编码传递到汤,.decode('latin-1'),但我什么都没得到。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

这应该是你想要的东西:

from BeautifulSoup import BeautifulSoup as bs
import urllib as ul

base_url = 'http://www.yellowpages.ca'
data_file = open('yellow_file.txt', 'a')

bt = bs(ul.urlopen(base_url + '/locations/Quebec/Montreal/90014002.html'))

for div in bt.findAll('div', 'ypgCategory'):
    for a in div.findAll('a'):
        link = base_url + a['href']

        bt = bs(ul.urlopen(link), convertEntities=bs.HTML_ENTITIES)

        titles = bt.findAll('span', 'listingTitle')
        phones = bt.findAll('a', 'phoneNumber')

        for title, phone in zip(titles, phones):
            line = '%s   %s\n' % (title.text, phone.text)
            data_file.write(line.encode('utf-8'))
            print line.rstrip()

data_file.close()

答案 1 :(得分:0)

谁告诉您使用latin-1解码UTF-8的内容? (在元标记上明确指定)

  1. 如果您在Windows上存储,则可能无法将Unicode输出到控制台,最好先测试写入文本文件。

  2. 如果您以文本形式打开文件,请不要写二进制文件:

    • codecs.open(...,"w","utf-8").write(unicode_str)
    • open(...,"wb").write(unicode_str.encode("utf_8"))