1. 程式人生 > >PHP簡單爬蟲&HTML DOM解析器&抓取網站內容

PHP簡單爬蟲&HTML DOM解析器&抓取網站內容

PHP簡單爬蟲&HTML DOM解析器&抓取網站內容

簡介

為了能簡單地用PHP爬取網站上的內容,用了HTMLDOM解析器簡單地抓取內容。練習下如何地神奇。
simple_html_dom的下載文件地址:線上文件
為了方便這是解析器檔案:檔案下載

例項

網站的抓取比較廣,就不多分析了,只是簡單地網頁抓取測試。

例如你的網頁index.html

<ul class="list">
	<li>
		<a heft="index.html">抓取的資料內容</a>
	</li>
</ul>

php程式碼

<?php
header("Content-type:text/html;charset=utf-8"); //引用解析器檔案 include_once 'simple_html_dom.php'; //使用file_get_html獲取html資料轉化為物件 //你要轉化的網站地址index.html $html = file_get_html('index.html'); //在類標籤內class='list',使用find方法查詢資料內容 foreach($html->find('.txt-list li a') as $element) //多條資料行可以用<br />等劃分,例如:innertext . <br>。
$arr[]= $element->innertext; //自動生成檔案 $fileName='data.txt'; $arrLen=count($arr); for($i=0;$i<$arrLen;$i++){ //FILE_APPEND|LOCK_EX 是往後追加資料 file_put_contents($fileName,$arr[$i],FILE_APPEND|LOCK_EX); } //抓取的資料儲存到data.txt $content=file_get_contents($fileName); $cont=explode("<br>",$content); $contLen
=count($cont); for($i=0;$i<$contLen;$i++) { unset($cont[2*$i+1]); }