1 // 抓取,添加数据 2 public function save(){ 3 require 'QueryList/phpQuery.php'; 4 require 'QueryList/QueryList.php'; 5 // 要抓的网址 6 $url = 'http://www.techweb.com.cn/newgame'; 7 $rules = 8 [ 9 'title' => ['.news_title>h3>a','html'], 10 'text' => ['.news_text>p','html'], 11 'img' => ['.na_pic>img','src'] 12 ]; 13 $data = @QueryList::Query($url,$rules)->data; 14 // 将数据中的图片循环保存 15 foreach ($data as $key=>$val){ 16 $res = file_get_contents($val['img']); 17 // 固定保存到指定文件夹中 18 $info = 'img/'.time().rand(1,999999).substr($val['img'],strrpos($val['img'],'.')); 19 file_put_contents($info,$res); 20 } 21 // 用Db方法把抓取数据存到数据表“query”中 22 Db::table('query')->insertAll($data,true); 23 }
如果抓取的数据有的无字段,则要添加判断条件
在给$data赋值完,图片循环保存之前添加判断
1 foreach ($data as $k=>$v) { 2 if (empty($v['title'])) { 3 unset($data[$k]); 4 } 5 if (empty($v['img'])) { 6 unset($data[$k]); 7 } 8 if (empty($v['text'])) { 9 unset($data[$k]); 10 } 11 }