I'm trying open and parse some html. So far, it was ok, I'm able to open the source and print it for example. But when it comes to parsing I'm stuck with "ElementTree instance has no attribute 'fromstring'"
this is my Django view.py 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
Do anyone have some idea, please?
Your import statement is wrong... fromstring
is a free function in the xml.etree.ElementTree
module, not a method of the class xml.etree.ElementTree.ElementTree
:
from xml.etree import ElementTree as etree
...
tree = etree.fromstring(r)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With