1.获取网页内容`
$content=file_get_contents("https://www.jd.com/");
$html=new DOMDocument();
$html->preserveWhiteSpace=false;
@$html->loadHTML($content);
$links=$html->getElementsByTagName('a');
2解析地址参考xml,DOMDocument
地址分类与拼接,构建一个完成url,后继续访问重复
保存数据
$linklist=array();
foreach($links as $link){
// echo $link->nodeValue."<br/>";
// //超链接文本
// echo $link->attributes->item(0)->nodeValue."<br/>";
// //超链接的属性对应的值
foreach($link->attributes as $atr){
//找到href属性
if($atr->nodeName=="href"){
if(strpos($atr->nodeValue,'/')==0){
array_push($linklist,'https://www.jd.com/'.$atr->nodeValue);
}else if(strpos($atr->nodeValue,'http://')==0){
array_push($linklist,$atr->nodeValue);
}
}
}
}
set_time_limit(0);
foreach($linklist as $link){
$filename=str_replace("https://www.jd.com/","",$link);
$filename=str_replace("/","-",$filename);
$content=file_get_contents($link);
file_put_contents("./download/html/$filename.html",$content);
echo "下载成功:$filename</br>";
ob_flush();
flush();
sleep(0.5);
}
2使用第三方库simple
include_once "simple_html_dom.php";
$html=file_get_html('https://www.jd.com/');
//查找超链接
// $links=$html->find('a');
// foreach($links as $link){
// echo $link->href."<br/>";
// }
//查找图片
$images=$html->find('img');
set_time_limit(0);
foreach($images as $image){
$src= $image->src;
if(strpos($src,'/')==0){
$url='https://www.jd.com/'.$src;
//拼接图片的URL
}else if(strpos($src,'http')==0){
$url=$src;
//以http开头
}
//下载
$filename=end(explode("/",$url));
//分割符号获取最后一个就是/
$content=file_get_contents($url);
file_put_contents("./download/img/$filename",$content);
echo "图片:$filename 下载完成</br>";
ob_flush();
flush();
sleep(0.5);
}
3使用正则表达式正则表达式解析页面元素
将html源码理解为很长的字符串
设定左右边界
$content=file_get_contents("https://www.jd.com/");
$patten='/<a href="(.*)"/';//贪婪模式
$patten='/<a href="(.+?)"/';//非贪婪模式
preg_match_all($patten,$content,$result);
print_r( $result);