• cURL 学习笔记与总结(2)网页爬虫、天气预报


    例1.一个简单的 curl 获取百度 html 的爬虫程序(crawler):

    spider.php

    <?php
    /*
        获取百度html的简单网页爬虫
    */
    $curl = curl_init('http://www.baidu.com'); //resource(2, curl)
    curl_exec($curl);
    curl_close($curl);

    访问该页面:

    例2.下载一个网页(百度)并把内容中的百度替换成'PHP'之后输出

    <?php
    /*
        下载一个网页(百度)并把内容中的百度替换成'PHP'之后输出
    */
    $curl = curl_init(); 
    curl_setopt($curl, CURLOPT_URL, 'http://www.baidu.com'); //设置访问网页的url
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);         //执行之后不直接打印出来
    $output = curl_exec($curl);     //执行
    curl_close($curl);                //关闭cURL
    echo str_replace('百度','PHP',$output);

    访问该页面:

    例3.调用 WenService 获取天气信息

    WeatherWS(http://www.webxml.com.cn/WebServices/WeatherWS.asmx?op=getWeather) 提供了多种方式获取天气信息,例如 soap1.1,soap1.2,http get,http post。

    现在使用 curl 模拟 http post 来获取天气数据。

    weather.php

    <?php
    /*
        cURL调用WebService查询北京的当前天气 
    */
    $data = 'theCityName=北京';
    $curl = curl_init();
    curl_setopt($curl,CURLOPT_URL,'http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName');
    curl_setopt($curl,CURLOPT_HEADER,0);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($curl,CURLOPT_POST,1); //post方式
    curl_setopt($curl,CURLOPT_POSTFIELDS,$data); //设置post的参数
    curl_setopt($curl,CURLOPT_HTTPHEADER,array('application/x-www-form-urlencoded;charset=utf-8','Content-length: '.strlen($data)));
    curl_setopt($curl, CURLOPT_USERAGENT, "user-agent:Mozilla/5.0 (Windows NT 5.1; rv:24.0) Gecko/20100101 Firefox/24.0"); //解决错误:“未将对象引用设置到对象的实例。”
    $rtn = curl_exec($curl);
    if(!curl_errno($curl)){
        //$info = curl_getinfo($curl);
        //print_r($info);
        echo $rtn;
    }else{
        echo 'curl error: '.curl_error($curl);
    }
    curl_close($curl);

    页面输出:

    也可以在 cmd 中使用:

    C:UsersAdministrator>d:
    
    D:>cd practise/php/curl
    
    D:practisephpcurl>php -f weather.php > weather.txt

    把返回的结果保存在 txt 文件中(如果报错,参考 php运行出现Call to undefined function curl_init()的解决方法)。

  • 相关阅读:
    独木舟上的旅行
    会场安排问题
    喷水装置(二)
    喷水装置(一)
    款待奶牛
    整理书本
    贪心算法基本思想和典型例题(转)
    贪心算法
    太乱了,不要了
    Runtime Error:Floating point exception 不知道拿错了
  • 原文地址:https://www.cnblogs.com/dee0912/p/4374817.html
Copyright © 2020-2023  润新知