十分钟带你了解PHP实现爬虫的过程

文字信息

我们尝试获取表的信息,这里,我们就用某校的课表来代替:

0ecc9cfea85a341809c2bdd29f38956.png

接下来我们就上代码:

a.php

 <?php  header( Content-type:text/html;Charset=utf-8 ); 
$ch = curl_init();        $url =表的链接;
        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);
        preg_match_all(/<td rowspan=\\d\>(.*?)<\/td>\n<td rowspan=\\d\>(.*?)<\/td><td rowspan=\\d\ align=\\w+\>(.*?)<\/td><td rowspan=\\d\ align=\\w+\>(.*?)<\/td><td>(.*?)<\/td>\n<td>(.*?)<\/td><td>(.*?)<\/td>/,$content,$matchs,PREG_SET_ORDER);//匹配该表所用的正则
        var_dump($matchs);

然后咱们就运行一下:

86be9358af8f31f62aff6c5f0ecdf2c.png

成功获取到课表;

图片获取

绝对链接

我们以百度图库的首页为例

这里写图片描述


b.php

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


    $ch = curl_init();    $url=http://image.baidu.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>;
     }

然后,我们就获得了下面的页面:

48a346477b12991947057f19787aacd.png

相对链接

百度图库的图片的链接大部分是绝对链接,那么当我们遇到网页图片为相对链接的时候,我们该怎么处理呢?其实很简单,我们只需要将循环那部分改为

e90d1406e7367a25cb1e67578c3d8a8.png

那么我们就可以同样在浏览器中输出图片了;

感谢大家的阅读,希望大家有所收益。

推荐教程:《php教程

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...