python - 查找具有特定属性值的所有标签

标签 python html-parsing lxml

如何迭代具有特定属性和特定值的所有标签?例如,假设我们只需要 data1、data2 等。

<html>
    <body>
        <invalid html here/>
        <dont care> ... </dont care>
        <invalid html here too/>
        <interesting attrib1="naah, it is not this"> ... </interesting tag>
        <interesting attrib1="yes, this is what we want">
            <group>
                <line>
                    data
                </line>
            </group>
            <group>
                <line>
                    data1
                <line>
            </group>
            <group>
                <line>
                    data2
                <line>
            </group>
        </interesting>
    </body>
</html>

我尝试了 BeautifulSoup 但它无法解析该文件。不过,lxml 的解析器似乎可以工作:

broken_html = get_sanitized_data(SITE)

parser = etree.HTMLParser()
tree = etree.parse(StringIO(broken_html), parser)

result = etree.tostring(tree.getroot(), pretty_print=True, method="html")

print(result)

我不熟悉它的 API,也不知道如何使用 getiterator 或 xpath。

最佳答案

这是一种方法,使用 lxml 和 XPath 'descendant::*[@attrib1="是的,这就是我们想要的"]'。 XPath 告诉 lxml 查看当前节点的所有后代,并返回 attrib1 属性等于“是的,这就是我们想要的” 的后代。

import lxml.html as lh 
import cStringIO

content='''
<html>
    <body>
        <invalid html here/>
        <dont care> ... </dont care>
        <invalid html here too/>
        <interesting attrib1="naah, it is not this"> ... </interesting tag>
        <interesting attrib1="yes, this is what we want">
            <group>
                <line>
                    data
                </line>
            </group>
            <group>
                <line>
                    data1
                <line>
            </group>
            <group>
                <line>
                    data2
                <line>
            </group>
        </interesting>
    </body>
</html>
'''
doc=lh.parse(cStringIO.StringIO(content))
tags=doc.xpath('descendant::*[@attrib1="yes, this is what we want"]')
print(tags)
# [<Element interesting at b767e14c>]
for tag in tags:
    print(lh.tostring(tag))
# <interesting attrib1="yes, this is what we want"><group><line>
#                     data
#                 </line></group><group><line>
#                     data1
#                 <line></line></line></group><group><line>
#                     data2
#                 <line></line></line></group></interesting>

关于python - 查找具有特定属性值的所有标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3778512/

相关文章:

python - 使用 BeautifulSoup 查找具有特定子元素的元素

java - 如何从网页中提取句子

Python lxml.html XPath "attribute not equal"运算符未按预期工作

python - 实体引用和 lxml

python - lxml 和循环在 python 中创建 xml rss

python - 如何检查 Python 模块的版本?

python - 基于某种格式的字符串排序

python - 如何在Python中使用小数有效计算立方根

python - YouTube 视频速率 API 不会增加喜欢/不喜欢计数器

java html解析器不读取所有页面