Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

python - saving an 'lxml.etree._ElementTree' object

I've spent the last couple of days getting to grips with the basics of lxml; in particular using lxml.html to parse websites and create an ElementTree of the content. Ideally, I want to save the returned ElementTree so that I can load it up and experiment with it, without having to parse the website every time I modify my script. I assumed that pickling would be the way to go, however I'm now beginning to wonder. Although I am able to retrieve an ElementTree object after pickling...

type(myObject) 

returns

<class 'lxml.etree._ElementTree'>

the object itself appears to be 'empty', since none of the subsequent method/attribute calls I make on it yield any output.

My guess is that pickling isn't appropriate here, but can anyone suggest an alternative?

(In case it matters, the above is happening in: python3.2, lxml 2.3.2, snow-leopard))

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are already dealing with XML, and lxml is great at parsing XML. So I think the simplest thing to do would be to serialize to XML:

To write to file:

import lxml.etree as ET

filename = '/tmp/test.xml'
myobject.write(filename)

To call the write method, note that myobject must be an lxml.etree._ElementTree. If it is an lxml.etree._Element, then you would need myobject.getroottree().write(filename).

To parse from file name/path, file object, or URL:

myobject = ET.parse(file_or_url)

To parse from string:

myobject = ET.fromstring(content)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...