【问题标题】:PHP crawler: Check if object existsPHP爬虫:检查对象是否存在
【发布时间】:2012-06-30 16:35:54
【问题描述】:

我在寻找某些类/元素的页面上运行 php 脚本,如果类/元素不存在,我有时可能会收到 “尝试获取非对象的属性” 错误.

我想知道如何处理此错误,以便我可以将自己的 null 值分配给变量,因为使用 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");

【问题讨论】:

    标签: php dom web-crawler


    【解决方案1】:

    在尝试访问其属性之前,您应该首先检查find 的结果:

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

    这适用于foreach 内的所有 3 个检查,仅具有不同的参数名称等。

    【讨论】:

    • @mk_89:不,这肯定不是你正在做的。您正在检查 $result-&gt;property,而不是 $result 本身。
    • 啊,我看到了问题,我不应该将其转换为 if 语句的纯文本。
    猜你喜欢
    • 1970-01-01
    • 2015-07-28
    • 2016-01-08
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多