【问题标题】:XHTML namespace issues with cssselect in lxmllxml 中 cssselect 的 XHTML 命名空间问题
【发布时间】:2011-10-15 03:47:54
【问题描述】:

我在使用带有 XHTML(或带有命名空间的 XML)的 cssselect 时遇到问题。虽然文档说如何在 csselect 中使用命名空间,但我不明白:cssselect namespaces

我的输入 XHTML 字符串:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Teststylesheet</title>
  <style type="text/css">
  /*<![CDATA[*/
  ol{margin:0;padding:0}
  /*]]>*/
  </style>
</head>
<body>
</body>
</html>

我的 Python 脚本:

parser = etree.XMLParser()    
tree = etree.fromstring(xhtmlstring, parser).getroottree()
for style in CSSSelector("style")(tree):
  print "HAVE CSS!"

python 脚本不打印任何Have CSS!。使用etree.HTMLParser 而不是etree.XMLParser 可以,但我真的很想使用XMLParser 并保留XHTML 的所有内容(命名空间、结构)。

谁能帮我解决这个命名空间问题?

【问题讨论】:

    标签: python css xhtml lxml xml-namespaces


    【解决方案1】:

    cssselect.CSSSelector(2.0 版)的文档字符串显示了如何使用命名空间:

    class CSSSelector(etree.XPath):
        """ ...
        To use CSS namespaces, you need to pass a prefix-to-namespace
        mapping as ``namespaces`` keyword argument::
    
            >>> rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
            >>> select_ns = cssselect.CSSSelector('root > rdf|Description',
            ...                                   namespaces={'rdf': rdfns})
    
            >>> rdf = etree.XML((
            ...     '<root xmlns:rdf="%s">'
            ...       '<rdf:Description>blah</rdf:Description>'
            ...     '</root>') % rdfns)
            >>> [(el.tag, el.text) for el in select_ns(rdf)]
            [('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description', 'blah')]
        """
    

    如果您尝试过此操作,但您的cssselect.CSSSelector 版本没有namespaces 参数,那么您的lxml 版本可能需要升级。

    【讨论】:

    • 谢谢!我刚刚用for style in CSSSelector("xhtml|style", namespaces={'xhtml': 'http://www.w3.org/1999/xhtml'})(tree): 替换了我的代码for style in CSSSelector("style")(tree): 中的字符串,它工作了!在我看来,cssselect 和命名空间的文档可以改进。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多