簡體   English   中英

PHP爬蟲:檢查對象是否存在

[英]PHP crawler: Check if object exists

我在一個尋找某些類/元素的頁面上運行一個php腳本,如果類/元素不存在,我有時會得到“試圖獲取非對象的屬性”錯誤。

我想知道如何處理這個錯誤,以便我可以將自己的空值賦給變量,因為使用if語句或is_null似乎沒有做到這一點。

查看下面的代碼,以便更好地理解我的意思。

在行上if($size = $elem->find('.size',0)->plaintext)並且將為'history'元素拋出錯誤,因為類大小不存在。

功能:的getInfo

function getInfo($link){
   $page = file_get_html($link);        

   if($page){       
      $categoryLink = array();
      $categoryName = array();
      $categorySize = array();

      if($container = $page->find('.infoContainer',1)){

         foreach($container->find('.element') as $elem){

            if($link = $elem->find('a',0)->href){   
               $categoryLink[] = $link;
            }else{
               $categoryLink[] = "";
            }

            if($name = $elem->find('.name',0)->plaintext){
               $categoryName[] = $name;
            }else{
               $categoryName[] = "";
            }

            if($size = $elem->find('.size',0)->plaintext){
               $categorySize[] = $size;
            }else{
               $categorySize[] = 0;
            }
         }
      }
   }
}

www.example.com

<div class='infoContainer'>
   <div class='element'>
      <a href='www.example.com/physics'>
      <div class='name'>physics</div>
      <div class='size'>1000</div>
   </div>
   <div class='element'>
      <a href='www.example.com/math'>
      <div class='name'>math</div>
      <div class='size'>800</div>
   </div>
   <div class='element'>
      <a href='www.example.com/history'>
      <div class='name'>history</div>
   </div>

</div>

通話功能

getInfo("www.example.com");

在嘗試訪問其屬性之前,您應首先檢查find結果:

$result = $elem->find('foo', 0);
if ($result) {
    $something = $result->property;
}

這適用於foreach內的所有3個檢查,僅適用於不同的參數名稱等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM