有人有使用lxml.html中element.sourceline方法的示例吗?
我希望我问得对。我正在试着弄明白element.sourceline这个东西是干嘛的,以及有没有什么方法可以利用它的功能。我尝试了很多种方式来构建我的元素,但每次我遍历这些元素并询问sourceline时,总是得到None。当我试着使用内置的帮助功能时,也没有得到任何信息。
我在网上搜索过示例,但还没有找到。
我知道这是元素的方法,而不是树的方法,但这也是我目前能想到的最好解释。
这是对Jim Garrison请求示例的回应
theTree=html.parse(open(r'c:\temp\testlxml.htm'))
check_source
the_elements=[(e,e.sourceline) for e in theTree.iter()] #trying to get the sourceline
for each in the_elements:
if each[1]!=None:
check_source.append(each)
当我运行这个时,len(check_source)==0
我的html文件有19,379行,所以我不确定你是否想看看它
我尝试了一个解决方案
>>> myroot=html.fromstring(xml)
>>> elementlines=[(e,e.sourceline) for e in myroot.iter()]
>>> elementlines
[(<Element doc at 12bb730>, None), (<Element foo at 12bb650>, None)]
当我用etree做同样的事情时,我得到了展示的结果
>>> myroot=etree.fromstring(xml)
>>> elementlines=[(e,e.sourceline) for e in myroot.iter()]
>>> elementlines
[(<Element doc at 36a6b70>, 1), (<Element foo at 277b4e0>, 2)]
但是我的源html太乱了,我无法用etree来探索树,我得到了一个错误
1 个回答
5
sourceline
会返回在解析文档时确定的行号。所以它不会适用于通过API添加的元素。举个例子:
from lxml import etree
xml = '<doc>\n<foo>rain in spain</foo>\n</doc>'
root = etree.fromstring(xml)
print root.find('foo').sourceline # 2
root.append(etree.Element('bar'))
print etree.tostring(root)
print root.find('bar').sourceline # None
我很确定 lxml.html
也是这样。