PHP 爬虫

学习参考小结

Posted by 白 on April 2, 2019

简单获取百度title

<?PHP
   // 通过 file_get_contents 函数获取百度页面源码
   $html = file_get_contents("https://www.baidu.com/index.html");

   // 通过 preg_replace 函数使页面源码由多行变单行
   $htmlOneLine = preg_replace("/\r|\n|\t/","",$html);

   // 通过 preg_match 函数提取获取页面的标题信息
   preg_match("/<title>(.*)<\/title>/iU",$htmlOneLine,$titleArr);

   // 由于 preg_match 函数的结果是数组的形式
   $title = $titleArr[1];

   // 通过 echo 函数输出标题信息
   echo $title;
?>

乱码解决

<?PHP
   // 乱码解决办法,把其他编码格式通过 mb_convert_encoding 函数统一转为 UTF-8 格式
   $html = mb_convert_encoding($html,'UTF-8','UTF-8,GBK,GB2312,BIG5');
   // 还有一种因为gzip所以出现乱码的,我会在以后讲
?>

获取不到标题信息

<?PHP
// 获取不到标题信息解决办法,首先判断是否能获取到页面源码
// 如果能获取到但还是不能获取到标题信息
// 我猜测的问题是:因为是使用正则表达式获取的,源码没有变成一行,获取起来就会出现问题
$htmlOneLine=preg_replace("/\r|\n|\t/","",$html);
?>

获取不到页面源码

<?PHP
   // 像新浪微博你可能获取到的是“Sina Visitor System”
   // 解决办法添加header信息
   $opts = array(
   	'http'=>array(
		'method'=>"GET",
		"timeout"=>20,
		'header'=>"User-Agent: Spider \r\n",
   	)
   );
   $context = stream_context_create($opts);
   $html = file_get_contents($domain,0,$context,0,150000);
   // 这样就能获取到新浪微博的页面了
?>

爬取图片

<?php
header("Content-type:text/html;Charset=utf-8");

$ch = curl_init();
$url = "https://pixabay.com/";
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.113 Safari/537.36");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
$string = file_get_contents($url);
preg_match_all("/<img([^>]*)\s*src=('|\")([^'\"]+)('|\")/",
    $string, $matches);
$new_arr = array_unique($matches[3]);
foreach ($new_arr as $key) {
    echo "<img src=$key>";
}