详解使用PHP编写爬虫的方法

 4292

说到爬虫,大家的第一印象就会想到Python, 但是Python并不是所有人都会的, 那么是否可以使用其他的语言来编写爬虫呢? 当然是可以的,下面介绍一下如何使用PHP编写爬虫。


获取页面html内容

1、使用函数 file_get_contents 把整个文件读入一个字符串中。

  1. file_get_contents(path,include_path,context,start,max_length);
  2. file_get_contents('https://fengkui.net/');

这样就可以将整个页面的html内容,读入一个字符串中,然后进行解析了


2、使用CURL进行请求,获取html

  1. /**
  2.  * [curlHtml 获取页面信息]
  3.  * @param  [type] $url [网址]
  4.  * @return [type]      [description]
  5.  */
  6. function curlHtml($url)
  7. {
  8.     $curl = curl_init();
  9.     curl_setopt_array($curl, array(
  10.         CURLOPT_URL            => "{$url}",
  11.         CURLOPT_RETURNTRANSFER => true,
  12.         CURLOPT_ENCODING       => "",
  13.         CURLOPT_MAXREDIRS      => 10,
  14.         CURLOPT_TIMEOUT        => 30,
  15.         CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
  16.         CURLOPT_CUSTOMREQUEST  => "GET",
  17.         CURLOPT_HTTPHEADER     => array(
  18.             "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  19.             "Accept-Encoding: gzip, deflate, br",
  20.             "Accept-Language: zh-CN,zh;q=0.9",
  21.             "Cache-Control: no-cache",
  22.             "Connection: keep-alive",
  23.             "Pragma: no-cache",
  24.             "Upgrade-Insecure-Requests: 1",
  25.             "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
  26.             "cache-control: no-cache"
  27.         ),
  28.     ));
  29.     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  30.     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  31.     $response = curl_exec($curl);
  32.     $err = curl_error($curl);
  33.     curl_close($curl);
  34.     if ($err) return false;
  35.     else return $response;
  36. }

使用Curl我们可以来进行其他操作,如模拟浏览器模拟登陆等一些高级操作。


解析页面HTML,获取所需数据

1、正则获取内容

  1. /**
  2.  * [get_tag_data 使用正则获取html内容]
  3.  * @param  [type] $html  [爬取的页面内容]
  4.  * @param  [type] $tag   [要查找的标签]
  5.  * @param  [type] $attr  [要查找的属性名]
  6.  * @param  [type] $value [属性名对应的值]
  7.  * @return [type]        [description]
  8.  */
  9. function get_tag_data($html,$tag,$attr,$value){
  10.     $regex = "/<$tag.*?$attr=\".*?$value.*?\".*?>(.*?)<\/$tag>/is";
  11.     preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER);
  12.     $data = isset($matches[1][0]) ? $matches[1][0] : '';
  13.     return $data;
  14. }
  15. $str = '<div class="feng">冯奎博客</div>';
  16. $value = get_tag_data($str, 'div', 'class', 'feng');


2、使用Xpath解析数据

XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言。 具体使用方法及相关介绍查看百度百科(XPath) 使用方法:

  1. /**
  2.  * [get_html_data 使用xpath对获取到的html内容进行处理]
  3.  * @param  [type]  $html [爬取的页面内容]
  4.  * @param  [type]  $path [Xpath语句]
  5.  * @param  integer $tag  [类型 0内容 1标签内容 自定义标签]
  6.  * @param  boolean $type [单个 还是多个(默认单个时输出单个)]
  7.  * @return [type]        [description]
  8.  */
  9. function get_html_data($html,$path,$tag=1,$type=true)
  10. {
  11.     $dom = new \DOMDocument();
  12.     @$dom->loadHTML("<?xml encoding='UTF-8'>" . $html); // 从一个字符串加载HTML并设置UTF8编码
  13.     $dom->normalize(); // 使该HTML规范化
  14.     $xpath = new \DOMXPath($dom); //用DOMXpath加载DOM,用于查询
  15.     $contents = $xpath->query($path); // 获取所有内容
  16.     $data = [];
  17.     foreach ($contents as $value) {
  18.         if ($tag==1) {
  19.             $data[] = $value->nodeValue; // 获取不带标签内容
  20.         } elseif ($tag==2) {
  21.             $data[] = $dom->saveHtml($value);  // 获取带标签内容
  22.         } else {
  23.             $data[] = $value->attributes->getNamedItem($tag)->nodeValue; // 获取attr内容
  24.         }
  25.     }
  26.     if (count($data)==1) {
  27.         $data = $data[0];
  28.     }
  29.     return $data;
  30. }


TAG标签:
本文网址:https://www.zztuku.com/index.php/detail-9022.html
站长图库 - 详解使用PHP编写爬虫的方法
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐