Frage

I loaded a xml file from internet, and parsed with lxml. But I couldn't get the content by 'element'.text. Both result and source are short, I will just write them.

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>

Code :

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

result :

None
None
None
War es hilfreich?

Lösung

Removing etree.HTMLParser gives you texts:

>>> 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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top