cURL 学习笔记与总结(2)网页爬虫、天气预报
2023-09-11 14:17:03 时间
例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:\Users\Administrator>d: D:\>cd practise/php/curl D:\practise\php\curl>php -f weather.php > weather.txt
把返回的结果保存在 txt 文件中(如果报错,参考 php运行出现Call to undefined function curl_init()的解决方法)。
相关文章
- 2万字硬核剖析网页自定义字体解析(css样式表解析、字体点阵图绘制与本地图像识别等)
- 《网页美工设计Photoshop+Flash+Dreamweaver从入门到精通》——1.2 网页美工常用工具
- 《网页美工设计Photoshop+Flash+Dreamweaver从入门到精通》——2.3 创建选择区域
- 网页路由的两种工作模式
- 学生HTML个人网页作业作品(游戏网站全套源码)
- font-spider利器对webfont网页字体压缩使用
- 实现网页版MQTT
- python爬虫 requests.get()返回值与html网页不一致
- Python 爬虫 之 爬虫的一些基本知识和基本操作(爬取视频、图片、获取网页源码等)整理