代码之家  ›  专栏  ›  技术社区  ›  significance

如何使用xpath和lxml从下面糟糕的html中选择这些元素?

  •  1
  • significance  · 技术社区  · 15 年前

    我想使用lxml和一些聪明的xpath从这个html中选择以下字符串。字符串将更改,但周围的html不会更改。

    我需要。。。

    • 19/11/2010
    • AAAAAA/01
    • Normal
    • United Kingdom
    • This description may contains <bold>html</bold> but i still need all of it!

    从。。。

    ...
    <p>
        <strong>Date:</strong> 19/11/2010<br>
        <strong>Ref:</strong> AAAAAA/01<br>
        <b>Type:</b> Normal<br>
        <b>Country:</b> United Kingdom<br>
    </p>
    <hr>
    <p>
        <br>
        <b>1. Title:</b> The Title<br>
        <b>2. Description: </b> This description may contains <bold>html</bold> but i still need all of it!<br>
        <b>3. Date:</b> 25th October<br>
    ...
    
    </p>
    
    ...
    

    到目前为止,我只想到了使用正则表达式和 re:match 试着把它拖出来,但是如果没有什么东西能让我得到 <p> 例如节点。

    如果不通过regex对字符串进行后期处理,有什么方法可以做到这一点吗?

    谢谢:)

    2 回复  |  直到 15 年前
        1
  •  2
  •   user357812user357812    15 年前

    很难看!有了这个适当的格式输入:

    <html>
    <p>
        <strong>Date:</strong> 19/11/2010<br/>
        <strong>Ref:</strong> AAAAAA/01<br/>
        <b>Type:</b> Normal<br/>
        <b>Country:</b> United Kingdom<br/>
    </p>
    <hr/>
    <p>
        <br/>
        <b>1. Title:</b> The Title<br/>
        <b>2. Description: </b> This description may contains <bold>html</bold> but i still need all of it!<br/>
        <b>3. Date:</b> 25th October<br/>
    </p>
    </html>
    

    最简单的情况:

    /html/p/strong[.='Date:']/following-sibling::text()[1]
    

    评估对象:

     19/11/2010
    

    所有这些都在一个:

    /html/p/*[self::strong[.='Date:' or .='Ref:']|
              self::b[.='Type:' or .='Country:']]
             /following-sibling::text()[1]
    

    复杂的一个:

    /html/p/node()[preceding-sibling::b[1][.='2. Description: ']]
                  [following-sibling::b[1][.='3. Date:']]
                  [not(self::br)]
    
        2
  •  0
  •   Dimitre Novatchev    15 年前

    这并不难。

    给定此XML文档:

    <html> 
    <p> 
        <strong>Date:</strong> 19/11/2010<br/> 
        <strong>Ref:</strong> AAAAAA/01<br/> 
        <b>Type:</b> Normal<br/> 
        <b>Country:</b> United Kingdom<br/> 
    </p> 
    <hr/> 
    <p> 
        <br/> 
        <b>1. Title:</b> The Title<br/> 
        <b>2. Description: </b> This description may contains <bold>html</bold> but i still need all of it!<br/> 
        <b>3. Date:</b> 25th October<br/> 
    </p> 
    </html> 
    

    我需要。。。

    • 2010年11月19日
    • AAAAAA/01号
    • 正常
    • 大不列颠联合王国

    此XPath表达式选择上述所有文本节点 :

    /*/p[1]/text()
    
    • 此描述可能包含html,但我仍然需要所有 是的!

    用这个 :

    /*/p[2]/b[2]/following-sibling::node()
                     [count(.|/*/p[2]/b[2]/following-sibling::br[1]/preceding-sibling::node()) 
                    = 
                      count((/*/p[2]/b[2]/following-sibling::br[1]/preceding-sibling::node()))
                     ]