【问题标题】:Avoid the header of box xpath and curl避免框 xpath 和 curl 的标题
【发布时间】:2015-07-01 04:24:47
【问题描述】:

我正在编写代码以使用 xpath 和 curl 获取 Web 数据。

这些代码得到 ul li 包含并工作。

但我不想得到标题..

我写了以下代码来避免标题但不能

if($row->item(0)->tagName != '<ul class="graybg"><li>مدل خودرو</li>  <li>مشخصات</li><li>قیمت نمایندگی</li><li>قیمت بازار آزاد</li></ul>')

完整代码。

$ch = curl_init ("http://www.pedal.ir/price/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1;      en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
 curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
 $page = curl_exec($ch);


$dom = new DOMDocument('1.0', 'utf-8');
libxml_use_internal_errors(true);
$dom->loadHTML($page);
libxml_clear_errors();
$xpath = new DOMXpath($dom);

$data = array();
$table_rows = $xpath-   >query('/html/body/div/div[1]/div/div/div/div/div/div/div[2]/ul '); // target   the row (the browser rendered <tbody>, but actually it really doesnt have one)

 if($table_rows->length <= 0) { // exit if not found
echo 'no table rows found';
exit;
 }

 foreach($table_rows as $tr) { // foreach row
   $row = $tr->childNodes;
  if($row->item(0)->tagName != '<ul class="graybg"><li>مدل خودرو</li>  <li>مشخصات</li><li>قیمت نمایندگی</li><li>قیمت بازار آزاد</li></ul>') { //  avoid headers
       $data[] = array(
         'moled' =>trim($row->item(0)->nodeValue),
         'detail' => trim($row->item(2)->nodeValue),
            'pricenama' => trim($row->item(4)->nodeValue),
            'pricebaza' => trim($row->item(6)->nodeValue),
    );
  }
  }

  echo '<pre>';
  print_r($data);;

【问题讨论】:

    标签: php html curl xpath domdocument


    【解决方案1】:

    作为替代方案,由于标头具有标识它的不同类,您可以将其包含在检查中:

    foreach($table_rows as $tr) { // foreach row
        $row = $tr->childNodes;
    
        if($row->item(0)->parentNode->getAttribute('class') !== 'graybg') { //  avoid headers
            $data[] = array(
                'moled' =>trim($row->item(0)->nodeValue),
                'detail' => trim($row->item(2)->nodeValue),
                'pricenama' => trim($row->item(4)->nodeValue),
                'pricebaza' => trim($row->item(6)->nodeValue),
            );
        }
    }
    

    Sample Output

    【讨论】:

      【解决方案2】:

      您可以将谓词[not(@class)] 添加到您的xpath 以过滤掉具有class 属性的&lt;ul&gt;:

      /html/body/div/div[1]/div/div/div/div/div/div/div[2]/ul[not(@class)]
      

      无论如何,绝对路径并不可靠,因为它往往会由于对 HTML 源代码的细微更改而中断。尝试基于元素的 id 或 class 构建您的 xpath。

      【讨论】:

        猜你喜欢
        • 2019-08-05
        • 2016-07-11
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-05
        相关资源
        最近更新 更多