php爬蟲實踐

來源:互聯網
上載者:User

標籤:

之前用nodejs的cheerio來做,不過nodejs的非同步回掉太噁心了,受不了。

後來發現了php的htmlpagedom庫,類似jquery的選取器文法,而且支援中文。

安裝  composer install wa72/htmlpagedom

1、讀取一個簡單的網頁,如:

require ‘vendor/autoload.php‘;use \Wa72\HtmlPageDom\HtmlPageCrawler;$url = "http://news.cnblogs.com/";$dom = HtmlPageCrawler::create(file_get_contents($url));print $dom->text(); //輸出內容

 

2、如何分析,使用jquery選取器文法,可以參考

如提取部落格園新聞首頁第一頁的所有連結,結構如下

$news_list = $dom->filter("#news_list");$news_entry =$news_list->filter(".news_entry");$urls = [];$i = 0;$url_cnt = $news_entry->count();//print $url_cnt; 30條,在瀏覽器裡尋找“發佈於”是30,證明是正確的while ($i<$url_cnt){    $urls[] = $news_entry->eq($i)->filter(‘a‘)->eq(0)->attr("href");    ++$i;}

可能有人疑問,為啥不用foreach

因為$news_entry->children() 返回的是DOMElement,而不是HtmlPageCrawler,不能使用filter,還要繼續用HtmlPageCrawler::create()。

3、提取新聞本文

 

$content = HtmlPageCrawler::create(file_get_contents($url.$urls[0]));

print $content->filter("#news_body")->text();

4、說明

有些網站的內容可能不是utf8的這時就要用iconv轉碼了

可以寫個函數封裝一下,$base根url,因為很多情況下連結是相對的。

function httpGet($url, $base = null) {    if (!$base) {        $url .= $base;    }    $html = file_get_contents($url);    $encode = mb_detect_encoding($html, "gbk,utf-8");    if (stripos($encode, "utf") !== false) {        return HtmlPageCrawler::create($html);    } else {        $utf_html = iconv("gbk", "utf-8", $html);        return HtmlPageCrawler::create($utf_html);    }}

如果用html()函數擷取html則輸出的都是html實體編碼,可以用html_entity_decode

另外可以用strip_tags 來去除html裡的某些標籤。

id是唯一的,而class和標籤都不是唯一的,所以擷取class和標籤,就算只有一個也要用eq(0)還擷取

 

jquery有個has函數判斷是否存在某個標籤,而HtmlPageCrawler缺少這個,於是手工添加了一個。

在HtmlPageCrawler.php的hasClass函數下面,添加如下代碼

    public function has($name) {        foreach ($this->children() as $node){             if ($node instanceof \DOMElement) {                $tagName = $node->tagName;                if (stripos($tagName, $name) !== false) {                    return true;                }            }        }        return false;    }

 

php爬蟲實踐

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.