An instance of ElementTree does not have the attribute 'fromstring'. So what have I done wrong?

I am trying to open and parse some html. While this was normal, I can open the source and print it, for example. But when it comes to parsing, I'm stuck in "Instance ElementTree does not have the attribute" fromstring ""

this is my Django view code:

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 Version: 1.2.4 Python Version: 2.6.5

Anyone have an idea please?

+5
source share
1 answer

Your import statement is wrong ... fromstringis a free function in a module xml.etree.ElementTree, not a class method xml.etree.ElementTree.ElementTree:

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

All Articles