通过pyquery获取具有特定属性的元素

时间:2018-10-17 08:55:00

标签: python pyquery

我在HTML页面中有类似的内容:

<ul>
    <li>
        <span data-name-en="data1">Value1</span>
        <span data-view-en="test1"><span class="fa fa-gear"></span></span>
    </li>
    <li>
        <span data-name-en="data2">Value2</span>
        <span data-view-en="test2"><span class="fa fa-gear"></span></span>
    </li>
    <li>
        <span data-name-en="data3">Value3</span>
        <span data-view-en="test3"><span class="fa fa-gear"></span></span>
    </li>
    <li>
        <span data-name-en="data4">Value4</span>
        <span data-view-en="test4"><span class="fa fa-gear"></span></span>
    </li>
</ul>

如何获取具有data-name-en属性的所有元素?

2 个答案:

答案 0 :(得分:0)

-- sh

答案 1 :(得分:0)

我找到了正确的答案:

s = '''
<ul>
    <li>
        <span data-name-en="data1">Value1</span>
        <span data-view-en="test1"><span class="fa fa-gear"></span></span>
    </li>
    <li>
        <span data-name-en="data2">Value2</span>
        <span data-view-en="test2"><span class="fa fa-gear"></span></span>
    </li>
    <li>
        <span data-name-en="data3">Value3</span>
        <span data-view-en="test3"><span class="fa fa-gear"></span></span>
    </li>
    <li>
        <span data-name-en="data4">Value4</span>
        <span data-view-en="test4"><span class="fa fa-gear"></span></span>
    </li>
</ul>
'''

html = PyQuery(s)
items = html.find('li span[data-name-en]')

要获取属性值,您需要执行以下操作:

pq(item).attr("data-name-en")