客体化和etree元素

时间:2013-11-27 01:23:33

标签: python lxml

我写过的模块与测试数据文件一起工作得很好,但对flickrapi的实时数据完全不知情。

经过几天的挫折之后(看,我有很多无事可做!)我想我发现了问题,但我不知道修复它的问题。

  • 内部测试数据返回类型():<type 'str'>
  • 外部测试数据返回类型():<type 'str'> ## opening&amp; 阅读外部XML
  • 实时数据返回类型():<class
    'xml.etree.ElementTree.Element'>

除了模块中的这一点,我使用了客观化。 Objectify解析<type 'str'>就好了,但 不会 读取etree元素。我我需要转换类&#39; xml.etree.ElementTree.Element&#39;到str(),但尚未怀疑它。

我从objectify.fromstring()得到的错误是:

Traceback (most recent call last):
    File "C:\Mirc\Python\Temp Files\test_lxml_2.py", line 101, in <module>
        Grp = objectify.fromstring(flickr.groups_getInfo(group_id=gid))
    File "lxml.objectify.pyx", line 1791, in lxml.objectify.fromstring (src\lxml\lxml.objectify.c:20904)
    File "lxml.etree.pyx", line 2994, in lxml.etree.fromstring (src\lxml\lxml.etree.c:63296)
    File "parser.pxi", line 1614, in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:93607)
ValueError: can only parse strings

在老板再次松开那些该死的飞猴之前请帮忙!!!

import fileinput
from lxml import html, etree, objectify
import re
import time
import flickrapi


if '@N' in gid:
    try:
        if tst:
            Grp = objectify.fromstring(test_data)
        else:
            Grp = objectify.fromstring(flickr.groups_getInfo(group_id=gid))

        fErr = ''
        mn = Grp.xpath(u'//group')[0].attrib
        res = Grp.xpath(u'//restrictions')[0].attrib
        root = Grp.group

        gNSID = gid
        gAlias = ""
        err_tst = getattr(root, "not-there", "Error OK")
        gName = getattr(root, "name", "")
        Images = getattr(root, 'pool_count', (-1))
        Mbr = getattr(root, "members", (-1))

2 个答案:

答案 0 :(得分:3)

解决方案是在调用objectify api之前停止将实时数据转换为xml.etree.ElementTree.Element个对象。

如果这是不可能的(我怀疑),您可以使用lxml.etree.tostring将xml渲染回文本表示,然后将其传递给etree.objectify.fromstring

答案 1 :(得分:1)

我认为传递给 objectify.fromstring 的“test_data”是String IO的实体,所以你必须首先阅读它然后客观化:

objectify.fromstring(test_data.read())
相关问题