【问题标题】:CSS selectors to query by attribute alone, with LXML使用 LXML 单独按属性查询的 CSS 选择器
【发布时间】:2015-07-06 13:04:43
【问题描述】:

我想获取属性包含 {% 的标签,例如以下示例:

<a href="{% route xy %}></a>
<img src="{% static xy %}/>

属性键无关紧要。

我能想到的最好的方法是tag.cssselect[href*={%],但当我想匹配所有属性而不考虑键时,它只匹配hrefs。

【问题讨论】:

  • 你必须为他们每个人定义。

标签: python css lxml


【解决方案1】:

如果可以接受,您可以使用 XPath 选择器来实现。 css selector is translated to XPath anyway-,就像这样:

//*[@*[contains(.,'{%')]]

上面的 XPath 选择具有包含"{%" 的任何属性的所有元素。以下是演示的工作示例:

from lxml.html import etree

html = """<div>
<a href="{% route xy %}"></a>
<img src="{% static xy %}"/>
</div>"""
root = etree.fromstring(html)
result = root.xpath("//*[@*[contains(.,'{%')]]")
for r in result:
    print etree.tostring(r)

输出:

<a href="{% route xy %}"/>

<img src="{% static xy %}"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2011-10-07
    • 2011-09-01
    • 1970-01-01
    相关资源
    最近更新 更多