【问题标题】:How to access comments using lxml如何使用 lxml 访问评论
【发布时间】: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()

【问题讨论】:

    标签: python html parsing lxml


    【解决方案1】:

    你可以剪掉字符串:

    from lxml.html import HtmlComment # or similar
    no_comments=[element for element in element_list if not isinstance(element, HtmlComment)]
    

    【讨论】:

    • 没有工作我的列表仍然包括 cmets 嗯,但它可能更早地工作 element_list 中的元素,如果它们是 cmets 是 cmets - 这有意义吗?作为注释的元素是 ,不是注释的元素是
    • 但它在这里确实有效 elements=[e for e in theTree.cssselect('text')[0].iter()) if not isinstance(e,HtmlComment)]
    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 2015-05-06
    • 1970-01-01
    相关资源
    最近更新 更多