php抓取網頁特定div區塊及圖片,從簡單入手


1. 取得指定網頁內的所有圖片:
<?php
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://yourweb/');
 
//取得第一個img標簽,並儲存至陣列match(regex語法與上述同義)
preg_match('/<img[^>]*>/Ui', $text, $match);
 
//打印match
print_r($match);
 
 
-----------------
2. 取得指定網頁內的第一張圖片:
<?php
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://yourweb/');
 
//取得第一個img標簽,並儲存至陣列match(regex語法與上述同義)
preg_match('/<img[^>]*>/Ui', $text, $match);
 
//打印match
print_r($match);
 
 
------------------------------------
 
 
3. 取得指定網頁內的特定div區塊(藉由id判斷):
<?php
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://yourweb/');
 
//去除換行及空白字元(序列化內容才需使用)
$text=str_replace(array("\r","\n","\t","\s"), '', $text); 
 
//取出div標簽且id為PostContent的內容,並儲存至陣列match
preg_match('/<div[^>]*id="PostContent"[^>]*>(.*?) <\/div>/si',$text,$match);
 
//打印match[0]
print($match[0]);
 
 
-------------------------------------------
4. 上述2及3的結合:
<?php
//取得指定位址的內容,並儲存至text
$text=file_get_contents('http://yourweb/'); 
 
//取出div標簽且id為PostContent的內容,並儲存至陣列match
preg_match('/<div[^>]*id="PostContent"[^>]*>(.*?) <\/div>/si',$text,$match); 
 
//取得第一個img標簽,並儲存至陣列match2
preg_match('/<img[^>]*>/Ui', $match[0], $match2);
 
//打印match2[0]
print_r($match2[0]);
 
轉載請聲明來源!
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM