我正在尝试打开并解析一些HTML。到目前为止,没关系,我可以打开源并打印它。但是当涉及到解析时,我仍然坚持“ElementTree实例没有属性'fromstring'”
这是我的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版本:1.2.4 Python版本:2.6.5
请问有人有什么想法吗?
答案 0 :(得分:15)
您的import语句错误... fromstring
是xml.etree.ElementTree
模块中的自由函数,而不是类xml.etree.ElementTree.ElementTree
的方法:
from xml.etree import ElementTree as etree
...
tree = etree.fromstring(r)