woff 發表於 2013-7-11 22:47:03

php抓取網頁特定div區塊及圖片

昨天有個朋友在問我說,php怎麼抓取網頁某個div區塊的內容。像funp推推王那樣每次推文都會顯示文章內的圖片,提供縮圖撰擇,又是怎麼做到的?其實這語法出乎意料的簡短…
http://andy.diimii.com/wp-temp/post/p224a.jpg1. 取得指定網頁內的所有圖片:測試



<?php

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/');   



//取得所有img標籤,並儲存至二維陣列match

preg_match_all('#<img[^>]*>#i', $text, $match);



//印出match

print_r($match);

?>



2. 取得指定網頁內的第一張圖片:測試



<?php

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/');



//取得第一個img標籤,並儲存至陣列match(regex語法與上述同義)

preg_match('/<img[^>]*>/Ui', $text, $match);



//印出match

print_r($match);

?>



3.取得指定網頁內的特定div區塊(藉由id判斷):測試




<?php

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/2009/01/seo%e5%8c%96%e7%9a%84%e9%97%9c%e9%8d%b5%e5%ad%97%e5%bb%a3%e5%91%8a%e9%80%a3%e7%b5%90/');   



//去除換行及空白字元(序列化內容才需使用)

//$text=str_replace(array("\r","\n","\t","\s"), '', $text);   



//取出div標籤且id為PostContent的內容,並儲存至陣列match

preg_match('/<div[^>]*id="PostContent"[^>]*>(.*?) <\/div>/si',$text,$match);



//印出match

print($match);

?>



4. 上述2及3的結合:測試


[*]<?php

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/2009/01/seo%e5%8c%96%e7%9a%84%e9%97%9c%e9%8d%b5%e5%ad%97%e5%bb%a3%e5%91%8a%e9%80%a3%e7%b5%90/');      



//取出div標籤且id為PostContent的內容,並儲存至陣列match

preg_match('/<div[^>]*id="PostContent"[^>]*>(.*?) <\/div>/si',$text,$match);   



//取得第一個img標籤,並儲存至陣列match2

preg_match('/<img[^>]*>/Ui', $match, $match2);   



//印出match2

print_r($match2);

?>


後記:用正規表達式Regex來做真的很方便,但老實說我規則常會忘掉,記錄一下幾篇文章好了(Regular Expression Details| PCRE Functions | Introduction to PHP Regex | 天殺的正規表示式…)
參考:Fetching the contents of a div tag by id
頁: [1]
查看完整版本: php抓取網頁特定div區塊及圖片