lxml将元素转换为elementtree

时间:2012-01-12 02:52:37

标签: python element lxml elementtree

以下测试读取文件,并使用lxml.html为页面生成DOM / Graph的叶节点。

但是,我也试图弄清楚如何从“字符串”获取输入。使用

 lxml.html.fromstring(s)

不起作用,因为这会生成“元素”而不是“ElementTree”。

所以,我正在试图弄清楚如何将元素转换为ElementTree。

思想

测试代码::

import lxml.html
from lxml import etree    # trying this to see if needed 
                          # to convert from element to elementtree


  #cmd='cat osu_test.txt'
  cmd='cat o2.txt'
  proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE)
  s=proc.communicate()[0].strip()

  # s contains HTML not XML text
  #doc = lxml.html.parse(s)
  doc = lxml.html.parse('osu_test.txt')
  doc1 = lxml.html.fromstring(s)

  for node in doc.iter():
  if len(node) == 0:
     print "aaa ",node.tag, doc.getpath(node)
     #print "aaa ",node.tag

  nt = etree.ElementTree(doc1)        <<<<< doesn't work.. so what will??
  for node in nt.iter():
  if len(node) == 0:
     print "aaa ",node.tag, doc.getpath(node)
     #print "aaa ",node.tag

===============================

更新:::

(解析html而不是xml) 添加了Abbas建议的更改。得到以下错误:

    doc1 = etree.fromstring(s)
  File "lxml.etree.pyx", line 2532, in lxml.etree.fromstring (src/lxml/lxml.etree.c:48621)
  File "parser.pxi", line 1545, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:72232)
  File "parser.pxi", line 1424, in lxml.etree._parseDoc (src/lxml/lxml.etree.c:71093)
  File "parser.pxi", line 938, in lxml.etree._BaseParser._parseDoc (src/lxml/lxml.etree.c:67862)
  File "parser.pxi", line 539, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:64244)
  File "parser.pxi", line 625, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:65165)
  File "parser.pxi", line 565, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:64508)
lxml.etree.XMLSyntaxError: Entity 'nbsp' not defined, line 48, column 220

UPDATE :::

管理以使测试正常运行。我不确定为什么。如果有人需要提供解释,这将有助于未来的人偶然发现这一点。

from cStringIO import StringIO
from lxml.html import parse

doc1 = parse(StringIO(s))

for node in doc1.iter():
    if len(node) == 0:
        print "aaa ", node.tag, doc1.getpath(node)

似乎StringIO模块/类实现了IO功能,它满足了解析包需要继续处理测试html的输入字符串。类似于铸造在其他语言中提供的......或者

感谢

3 个答案:

答案 0 :(得分:9)

要从_Element(使用lxml.html.fromstring生成)获取根树,您可以使用getroottree方法:

doc = lxml.html.parse(s)
tree = doc.getroottree()

答案 1 :(得分:2)

etree.fromstring方法解析XML字符串并返回根元素。 etree.ElementTree类是元素周围的树包装器,因此需要一个元素进行实例化。

因此,将根元素传递给etree.ElementTree()构造函数应该可以提供您想要的内容:

root = etree.fromstring(s)
nt = etree.ElementTree(root)

答案 2 :(得分:1)

_Element,通过如下调用返回:

tree = etree.HTML(result.read(), etree.HTMLParser())

可以像_ElementTree那样:

tree    = tree.getroottree() # convert _Element to _ElementTree

希望这就是你所期望的。