• PHP实现爬虫



    文字信息

    我们尝试获取表的信息,这里,我们就用某校的课表来代替:
    这里写图片描述
    接下来我们就上代码:

    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>
    <td rowspan="d">(.*?)</td><td rowspan="d" align="w+">(.*?)</td><td rowspan="d" align="w+">(.*?)</td><td>(.*?)</td>
    <td>(.*?)</td><td>(.*?)</td>/",$content,$matchs,PREG_SET_ORDER);//匹配该表所用的正则
            var_dump($matchs);

    然后咱们就运行一下:
    这里写图片描述
    成功获取到课表;

    图片获取

    绝对链接

    我们以百度图库的首页为例
    这里写图片描述
    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>";
         }

    然后,我们就获得了下面的页面:
    这里写图片描述

    相对链接

    百度图库的图片的链接大部分是绝对链接,那么当我们遇到网页图片为相对链接的时候,我们该怎么处理呢?其实很简单,我们只需要将循环那部分改为
    这里写图片描述
    那么我们就可以同样在浏览器中输出图片了;


    这里写图片描述
    扫码关注作者个人技术公众号,有关技术问题后台回复即可,不定期将有学习资源分享

    博客园:https://www.cnblogs.com/newtol 微信公众号:Newtol 【转发请务必保留原作者,否则保留追责权利】
  • 相关阅读:
    maven 创建web项目出错
    poj1699--Best Sequence(dfs+剪枝)
    HDU-1042-N!(Java大法好 &amp;&amp; HDU大数水题)
    “XXX.Index”不扩展类“System.Web.UI.Page”,因此此处不同意的问题
    scala模式匹配
    scala匿名函数
    scala特质
    group by的使用
    liux之我用过的zip解压命令
    liunx之zip格式的解压命令
  • 原文地址:https://www.cnblogs.com/newtol/p/10159135.html
Copyright © 2020-2023  润新知