【问题标题】:how to make a selection for the dictionary?如何选择字典?
【发布时间】:2014-03-10 17:18:03
【问题描述】:

请帮助编写 xpath-expression。

html:

<div class="TabItem">
    <p><strong>Product Composition</strong></p>
    <p>93% Polyamide 7% Elastane</p>
    <p>Lining: 100% Polyester</p><p>Dress Length: 90 cm</p>

    <p><strong>Product Attributes;</strong></p>
    <p>: Boat Neck, Long Sleeve, Midi, Zip, Concealed, Laced, Side</p>
    <p>Lining Type: Full Lining</p>
</div>

这需要获取以下html字典:

data['Product Composition'] = '93% Polyamide 7% Elastane Lining: 100% Polyester</p><p>Dress Length: 90 cm'
data['Product Attributes;'] = ': Boat Neck, Long Sleeve, Midi, Zip, Concealed, Laced, Side Lining Type: Full Lining'

元素的数量可以变化,这一点很重要。即你需要一个通用的解决方案

【问题讨论】:

    标签: python html xpath html-parsing lxml


    【解决方案1】:

    获取p 中的每个strong 标签,然后获取它的父级和下一个父级的兄弟姐妹,直到有另一个p 标记内部带有strong 标记或没有更多兄弟姐妹:

    from lxml.html import fromstring
    
    
    html_data = """<div class="TabItem">
        <p><strong>Product Composition</strong></p>
        <p>93% Polyamide 7% Elastane</p>
        <p>Lining: 100% Polyester</p><p>Dress Length: 90 cm</p>
    
        <p><strong>Product Attributes;</strong></p>
        <p>: Boat Neck, Long Sleeve, Midi, Zip, Concealed, Laced, Side</p>
        <p>Lining Type: Full Lining</p>
    </div>"""
    
    tree = fromstring(html_data)
    data = {}
    for strong in tree.xpath('//p/strong'):
        parent = strong.getparent()
    
        description = []
        next_p = parent.getnext()
        while next_p is not None and not next_p.xpath('.//strong'):
            description.append(next_p.text)
            next_p = next_p.getnext()
    
        data[strong.text] = " ".join(description)
    
    print data
    

    打印:

    {'Product Composition': '93% Polyamide 7% Elastane Lining: 100% Polyester', 
     'Product Attributes;': ': Boat Neck, Long Sleeve, Midi, Zip, Concealed, Laced, Side Lining Type: Full Lining'}
    

    【讨论】:

    • 但元素

      可能是不同的数字。现在是 2 个,但可能是 10 个和 1 个

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 2013-09-16
    • 2016-09-06
    • 2016-01-02
    • 2018-12-22
    相关资源
    最近更新 更多