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 }