LXML,巨蟒。我无法获得元素的内容:element.text是None

时间:2014-04-28 16:48:15

标签: python xml lxml

我从互联网上加载了一个xml文件,并用lxml进行了解析。但我无法通过'element'.text获取内容。结果和来源都很短,我只会写出来。

XML:

<?xml version="1.0" encoding="utf-8"?>
<products>
<product>
<company><![CDATA[google]]></company>
<link><![CDATA[http://www.google.com]]></link>
<subject><![CDATA[sushi]]></subject>
</product>
</products>

代码:

import urllib2
from lxml import etree
from StringIO import StringIO

rss = urllib2.urlopen("http://dizzy-v.co.kr/test/test.xml").read()
tree = etree.parse(StringIO(rss), etree.HTMLParser())

root = tree.getroot()
for product in root.iter('product'):
    for element in product.iter():
        print element.text

结果:

None
None
None

1 个答案:

答案 0 :(得分:2)

删除etree.HTMLParser会为您提供短信:

>>> import urllib2
>>> from lxml import etree
>>>
>>> rss = urllib2.urlopen("http://dizzy-v.co.kr/test/test.xml").read()
>>> root = etree.fromstring(rss) # <----
>>> for product in root.iter('product'):
...     for element in product.iter():
...         print element.text
...


google
http://www.google.com
sushi