这里抓取的是院校图标保存到本地,这里抓取图片主要是需要模仿浏览器去访问,不然获取不到数据。
<?php
$servername = "xx.xx.xx.xx";
$username = "xxx";
$password = "xxxxxx";
$dbname = "xxx";
$port = "3306";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname,$port);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
//模仿浏览器去访问
$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
$context = stream_context_create($opts);
$html = file_get_contents('https://www.wmzy.com/api/school/getSchList?page=1',false,$context);
preg_match_all('/\<img src\=(.|\n)*\>/U',$html,$conte);
foreach($conte[0] as $v){
preg_match_all('/school(.)*jpg/U',$v,$iurl);
$img = 'http://'.$iurl[0][0];
preg_match_all('/alt\=(.)*\>/U',$v,$nurl);
$name = str_replace('\" />',"",str_replace('alt=\"',"",$nurl[0][0]));
$src = array("/", "+", "=");
$dist = array("a", "b", "c");
$old = base64_encode($name);
$nename = 'D:/xampp/htdocs/img/'.str_replace($src,$dist,$old).'.jpg';
//$sql = "insert into ex_recruit_range(core,major,number,rang,cala,school_code,year) value ('$core','$major','$number','$range','$cala','$school_code','$year')";
//$sql = "insert into ex_recruit_range(core,major,number,rang,cala,school_code,year) value ('$core','$major','$number','$range','$cala','$school_code','$year')";
if ($conn->query($sql) === TRUE) {
//echo "新记录插入成功";
$count += 1;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
download('D:/xampp/htdocs/img/'.$name.'.jpg',$img);exit;
}
// $name = 'D:/xampp/htdocs/img/img0.jpg';
// $url = 'http://school-icon.b0.upaiyun.com/52ac2e9a747aec013fcf5307.jpg';
// download($name,$url);
function download($name, $url){
if(!is_dir(dirname($name))){
mkdir(dirname($name));
}
$str = file_get_contents($url);
file_put_contents(iconv("utf-8","gb2312",$name), $str);
//输出一些东西,要不窗口一直黑着,感觉怪怪的
echo strlen($str);
echo "\n";
}