[後端Jquery] - 輕量級無依賴 composer 超小巧的頁面抓取分析類

有時候咱們須要抓取一個頁面的一些信息來完成接口,用完curl獲得body後想獲取某個標籤的時候。 一看到正則委屈麼,委屈麼php


php 的 DOM 模塊

PHP自帶擴展 http://php.net/domhtml

<?php
/**
 * @author         Shaowei Pu <542684913@qq.cn>
 * @CreateTime    2017-04-17T19:25:59+0800
 */

$doc = new DOMDocument();

$html = <<<HTML_SECTION
<html><head><title>Sunyanzi's Test</title></head>
<body>
  <h1>Hello World</h1>
  <a href="http://segmentfault.com/" id="onlylink">Hey Welcome</a>
</body></html>
HTML_SECTION;

$doc->loadHTML( $html );

$h1Elements = $doc->getElementsByTagName( 'h1' );
foreach( $h1Elements as $h1Node ){
    echo $h1Node->nodeValue;
} 
echo $doc->getElementById( 'onlylink' )->getAttribute( 'href' );

$xpath = new DOMXPath( $doc );
// also prints "http://segmentfault.com/" ... locate via h1 ... 

echo $xpath->evaluate('string(//h1[text()="Hello World"]/following-sibling::a/@href)');

基本上, 等到你熟練掌握 XPath 以後 , 你會發現 DOM 比正則要靈活得多 ...node


PhpQuery

使用PhpQuery 徹底能夠省略curl抓取頁面的那一步,寫法徹底參照Jquerygit

https://github.com/TobiaszCud...github

/**
 * @author         Shaowei Pu <542684913@qq.cn>
 * @CreateTime    2017-04-17T19:25:59+0800
 */
      \phpQuery::newDocumentFile('https://v.qq.com/x/cover/o5neekjf0pl6e0r.html');  
         libxml_use_internal_errors(true);
        // 騰訊視頻的真實URL 
        $url = pq('link[rel="canonical"]')[0]->attr('href');

總結

  1. web 採集多樣性,若是不是抱着學習正則表達式的態度,應當靈活使用類庫web

  2. 偷懶萬歲!正則表達式

相關文章
相關標籤/搜索