2011-02-03 8 views
5

Estoy intentando abrir y analizar algunos html. Hasta el momento, estaba bien, puedo abrir la fuente e imprimirla, por ejemplo. Pero cuando se trata de análisis que estoy atascado con "instancia elementtree no tiene atributo 'fromstring'"instancia ElementTree no tiene atributo 'fromstring'. Entonces, ¿qué hice mal?

este es mi código de Django view.py:

from django.template import loader, Context 
from django.http import HttpResponse 
import urllib 
from xml.etree.ElementTree import ElementTree 

def transform (request): 
    opener = urllib.FancyURLopener({}) 
    f = opener.open("http://www.google.com/") 
    r = f.read() 
    f.close() 
    tree = ElementTree() 
    tree.fromstring(r) 
    p = tree.find("body/h1") 
    t = loader.get_template("transform.html") 
    c = Context({'neco': p }) 
    return HttpResponse(t.render(c)) 

Django Versión: 1.2.4 Versión Python : 2.6.5

¿Alguien tiene alguna idea, por favor?

Respuesta

13

Su declaración de importación está mal ... fromstring es una función gratuita en el módulo xml.etree.ElementTree, no es un método de la clase xml.etree.ElementTree.ElementTree:

from xml.etree import ElementTree as etree 
... 
tree = etree.fromstring(r) 
+1

que tiene sentido, pero ahora el guión toma el servidor hacia abajo. no estoy seguro de por qué. – Nanook

Cuestiones relacionadas