我在使用带有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的所有内容(名称空间,结构)。
有人可以帮我解决这个命名空间问题吗?
答案 0 :(得分:3)
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版本。