doubengshao8872
2014-07-29 14:47
浏览 26
已采纳

XPath - 在一些文本后选择锚点

I'd like to fetch data from this sample code:

<div id="text">

(sd) <a href="http://example.com/somefiledfs.flv">http://example.com/somefiledfs.flv</a>
 - 380 kbps 
 - <a href='/player.swf?config={"clip":{"url":"http://example.com/somefiledfs.flv"}'>Watch</a><br>

(576p) <a href="http://example.com/hgyj.mp4">http://example.com/hgyj.mp4</a>
 - 780 kbps 
 - <a href='/player.swf?config={"clip":{"url":"http://example.com/hgyj.mp4"}'>Watch</a><br>

</div>

I'd like to get it as:

sd - http://example.com/somefiledfs.flv

576p - http://example.com/hgyj.mp4

and so on.

Could sb help? I've beed trying to use "//div[@id='text']/a" and ancestor/preceding but I can't work it out.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • doujing5150 2014-07-29 19:40
    最佳回答

    Here's a working PHP snippet, basically loop over all links then check the previous node if it matches sd|576p (extend more formats here if needed...)

    <?php 
    $html = <<<HTML
    <div id="text">
      (sd) <a href="http://example.com/somefiledfs.flv">http://example.com/somefiledfs.flv</a>   
        - 380 kbps 
        - <a href='/player.swf?config={"clip":{"url":"http://example.com/somefiledfs.flv"}'>Watch</a><br>
    
      (576p) <a href="http://example.com/hgyj.mp4">http://example.com/hgyj.mp4</a>
        - 780 kbps 
        - <a href='/player.swf?config={"clip":{"url":"http://example.com/hgyj.mp4"}'>Watch</a><br>
    
    </div>
    HTML;
    
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    
    $as = $xpath->query("//div[@id='text']/a");
    
    foreach ($as as $a) {
      $prev = $a->previousSibling->nodeValue;
    
      if (preg_match("/sd|576p/", $prev, $matches)) {
        echo $matches[0]." - ".$a->nodeValue."
    ";
      }
    }
    ?>
    

    here's a link to the snippet: https://eval.in/173038

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题