1
imn1 May 8, 2015
看看出错时 article.findall('author') 是返回什么
另外不要一棵树上吊死,单纯研究还可以,做事的话不要纠结在一个问题 如果一个地方撞墙了,就绕一下弯,例如换 lxml 试试,或者换 xpath 试试 |
2
binux May 8, 2015
你的用法有误
https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.iterparse,看 Note: > iterparse() only guarantees that it has seen the “>” character of a starting tag when it emits a “start” event, so the attributes are defined, but the contents of the text and tail attributes are undefined at that point. 而当 end 的时候,你已经把 article.clear() 了 |
6
binux May 8, 2015
|
7
ivanchou OP @binux
好奇为什么在只注释掉 article.clear() 或者去掉 events=("start", "end") 的情况下都有问题,而两者都去掉就 OK 了。大神能不能再简单解释下。 还有 article 不需要及时 clear 吗?如果不及时 clear 那么跟直接 parse 有什么区别?我注意到占用内存以及开始飙升了。 |
8
binux May 8, 2015
@ivanchou 去掉 events=("start", "end") 之后,只有 end event 会被 pop 出来。根据 Note,start 的时候,子元素是不全的。
去掉 clear,因为你的 article 并不是只有 article 标签,如果在 article end 之前,把 author clear 了,那就取不到东西了。如果你要释放,在 26 行 clear 即可。 使用 iterparse 的正确的方法应该是把它看做一个状态机,想好在什么标签状态干什么。在 article.tag == 'author' 的时候输出 author, 在 article.tag == 'article' 的时候 clear 和换行,而不是用 findall。 |