采集百度圖片,用了火車頭,不知道怎么制定ajax頁面,最終只好自己寫了一個,原理很簡單,重點就是找到ajax頁面,而這個很簡單,打開百度圖片,搜索關鍵詞,進控制臺,切換到網絡模塊,查找即可。
前端頁面核心代碼
<form name="f" method="get"> 百度圖片 <input type="text" name="word" placeholder="關鍵詞"> <input type="text" name="p" placeholder="采集頁數"> <input type="submit" value="ok"> </form> <textarea id="show" style="width:700px;height:400px;"></textarea> <script type="text/javascript"> var dom=$('#show'); function showmsg(msg){ dom.val(dom.val()+msg+'\n'); dom.animate({"scrollTop":"+=20"},1); } </script>
其中,要采集的頁面可以參考百度圖片滾動加載的最大值;js是為了動態查看采集效果并輸出。用php的ob_flush(),如果你的無效,可以參考之前寫的:Ob_flush()無效,Win7無法打開ApplicationHost.Config。
后臺部分核心代碼:
set_time_limit(0); $d=I('get.'); $word=urlencode($d['word']);//搜索關鍵詞轉碼 $p=$d['p'];//采集最大頁碼 $i=0; while($i<$p){ $url='https://image.baidu.com/search/acjson?tn=resultjson_com&logid=9808852852719138370&ipn=rj&ct=201326592&is=&fp=result&queryWord='.$word.'&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=©right=&word='.$word.'&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&expermode=&force=&pn='.($i*30).'&rn=30&gsm=1e&1604382596389=';//ajax頁地址拼接 show_msg("開始采集第".($i+1)."頁");//實時輸出提示文字 $d=file_get_contents($url);//獲取頁面內容 preg_match_all('`,{"ObjURL":"(.*?)","ObjUrl":"`',$d,$imgs);//得到目標圖片地址 preg_match_all('`"fromPageTitleEnc":"(.*?)"`',$d,$tits);//得到目標圖片描述文字 $imgs=$imgs[1]; $tits=$tits[1]; foreach ($imgs as $key => $value) { $img=str_replace('\\','',$value);//json圖片url處理 if($img=file_get_contents($img)){ if($tits[$key]){ $title=$tits[$key].'_'.rand(100000,999999);//如果有對應的圖片描述 圖片以此為名 }else{ $title=date('YmdHis').'_'.rand(100000,999999);//否則 } file_put_contents('D:/pics/'.iconv('utf-8','gbk',$title).'.jpg', $img);//輸出中文文件名需要轉碼,否則會出現亂碼情況 show_msg("成功下載".$title);//輸出提示文字 } } $i++; }附上show_msg函數
function show_msg($msg){ echo "<script type=\"text/javascript\">showmsg('{$msg}');</script>"; ob_flush(); flush(); }
© 致遠 2020-11-04,原創內容,轉載請注明出錯:php采集百度圖片搜索結果內容