【发布时间】:2011-04-08 08:02:36
【问题描述】:
我正在尝试从使用 lxml 获得的元素列表中删除 cmets
我能做的最好的是:
no_comments=[element for element in element_list if 'HtmlComment' not in str(type(each))]
不知道有没有更直接的方法?
我将根据 Matthew 的回答添加一些内容 - 他让我几乎到了那里,问题是当元素从树中取出时,cmets 失去了一些身份(我不知道如何描述它)所以它使用isinstance()方法无法判断是否为HtmlComment类对象
但是,当元素在树上迭代时可以使用该方法
from lxml.html import HtmlComment
no_comments=[element for element in root.iter() if not isinstance(element,HtmlComment)
对于像我这样的新手来说,root 是包含树中所有其他元素的基本 html 元素,有很多方法可以获取它。一种是打开文件并遍历它,而不是上面的root.iter()
html.fromstring(open(r'c:\temp\testlxml.htm').read()).iter()
【问题讨论】: