2015-06-10 8 views
14

Voglio fare motore di ricerca e seguo il tutorial in qualche web. Voglio testare analizzare HTMLPython 3 UnicodeDecodeError: il codec 'charmap' non può decodificare il byte 0x9d

from bs4 import BeautifulSoup 

def parse_html(filename): 
    """Extract the Author, Title and Text from a HTML file 
    which was produced by pdftotext with the option -htmlmeta.""" 
    with open(filename) as infile: 
     html = BeautifulSoup(infile, "html.parser", from_encoding='utf-8') 
     d = {'text': html.pre.text} 
     if html.title is not None: 
      d['title'] = html.title.text 
     for meta in html.findAll('meta'): 
      try: 
       if meta['name'] in ('Author', 'Title'): 
        d[meta['name'].lower()] = meta['content'] 
      except KeyError: 
       continue 
     return d 

parse_html("C:\\pdf\\pydf\\data\\muellner2011.html") 

ed errore

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 867: character maps to <undefined>enter code here 

ottenere Ho visto alcune soluzioni sul Web utilizzando la codifica(). Ma non so come inserire la funzione encode() nel codice. Qualcuno può aiutarmi?

+0

Che cos'è il traceback ** completo ** dell'eccezione? –

risposta

30

In Python 3, i file sono testo aperto (decodificato in Unicode) per te; non devi dire a BeautifulSoup da quale codec decodificare.

Se la decodifica dei dati fallisce, è perché non hai detto al open() di chiamare quale codec usare durante la lettura del file; aggiungere il codec corretto con un argomento encoding:

with open(filename, encoding='utf8') as infile: 
    html = BeautifulSoup(infile, "html.parser") 

altrimenti il ​​file sarà aperto con il codec di default del sistema, che dipende dal sistema operativo.

Problemi correlati