首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 爬蟲實作:使用正則表達式擷取網頁圖片與特定 DIV 內容

     編輯:PHP 相關知識

1. 取得所有圖片標籤

<?php
$text = file_get_contents('https://www.jbxue.com/');
preg_match_all('/<img[^>]*>/i', $text, $match);
print_r($match);
?>

2. 取得第一張圖片

<?php
$text = file_get_contents('https://www.jbxue.com/');
preg_match('/<img[^>]*>/Ui', $text, $match);
print_r($match);
?>

3. 取得指定 ID 的 DIV 區塊

<?php
$text = file_get_contents('https://www.jbxue.com/');
preg_match('/<div[^>]*id="PostContent"[^>]*>(.*?)<\/div>/si', $text, $match);
print($match[0]);
?>

4. 綜合應用:先取 DIV 再取圖片

<?php
$text = file_get_contents('https://www.jbxue.com/');
preg_match('/<div[^>]*id="PostContent"[^>]*>(.*?)<\/div>/si', $text, $match);
preg_match('/<img[^>]*>/Ui', $match[0], $match2);
print_r($match2[0]);
?>

關鍵旗標說明:i 不分大小寫,U 非貪婪模式,s 讓 . 匹配換行符。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved