zoukankan      html  css  js  c++  java
  • 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 【转发请务必保留原作者,否则保留追责权利】
  • 相关阅读:
    python中的time模块
    CSS 布局
    8 Function类型
    2 node 核心
    1 node 简介
    13 对象
    JS 算法一
    JS 模块化
    1 谈谈section标签
    JS 练习一
  • 原文地址:https://www.cnblogs.com/newtol/p/10159135.html
Copyright © 2011-2022 走看看