2012-04-20 7 views
8

Vorrei analizzare un documento HTML utilizzando lxml. Sto usando Python 3.2.3 e lxml 2.3.4 (http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml)lxml errore etree.iterparse "TypeError: lettura degli oggetti del file deve restituire stringhe semplici"

Sto usando il etree.iterparse per analizzare il documento, ma restituisce il seguente errore di runtime:

Traceback (most recent call last): 
    File "D:\Eclipse Projects\Python workspace\Crawler\crawler.py", line 12, in <module> 
    for event, elements in etree.iterparse(some_file_like): 
    File "iterparse.pxi", line 491, in lxml.etree.iterparse.__next__ (src/lxml\lxml.etree.c:98565) 
    File "iterparse.pxi", line 512, in lxml.etree.iterparse._read_more_events (src/lxml\lxml.etree.c:98768) 
TypeError: reading file objects must return plain strings 

la domanda è: Come risolvere questo errore di runtime?

Grazie mille.

Ecco il codice:

from io import StringIO 
from lxml import etree 

some_file_like = StringIO("<root><a>data</a></root>") 

for event, elements in etree.iterparse(some_file_like): #<-- Run-time error happens here 
    print("%s, %4s, %s" % (event, elements.tag, elements.text)) 

risposta

18

il buffer StringIO ha stringa unicode. iterparse funziona con file come oggetti che restituiscono byte. Il seguente buffer dovrebbe funzionare con iterparse:

from io import BytesIO 
some_file_like = BytesIO("<root><a>data</a></root>".encode('utf-8')) 
+0

Grazie per il feedback. Ho provato il tuo suggerimento ma ha dato il seguente errore di run-time: TypeError: initial_value deve essere str o None, non byte –

+0

A quanto pare devi usare 'BytesIO' per byte e' StringIO' per stringhe (a differenza del vecchio 'StringIO' che potrebbe essere usato per entrambi). Risolto il problema con la mia risposta – Imran

+0

La correzione funziona. Grazie :) –

Problemi correlati