CURL库的一些用法总结(爬站…)
1.CURL库的基本步骤:
a)curl_init();
b)curl_setopt();
c)curl_exec();
d)curl_close();
2.重点解释curl_setopt里面的内容:
CURLOPT_RETURNTRANSFER:把他设置成1后,再执行curl_exec就不会直接输出到页面而是输出到制定的变量
CURLOPT_URL:设置连接,这个不用说了。
CURLOPT_HEADER:是否在输出的时候带着HTTP头。
CURLOPT_COOKIEFILE跟CURLOPT_COOKIEJAR:在这个里面设置好文件的打开句柄就可以将cookie以netscape方式保存下来
例子:
<?php
$cookieFilePath = dirname(__FILE__).”/cookies/cookie-”.getRand().”.txt”;
@unlink($cookieFilePath);
curl_setopt($login, CURLOPT_COOKIEFILE, $cookieFilePath);
curl_setopt($login, CURLOPT_COOKIEJAR, $cookieFilePath);
?>
CURLOPT_HTTPHEADER:在请求的时候,给远程服务器输入的HTTP头,以数组的形式给出:
例子:
<?php
curl_setopt($login,CURLOPT_HTTPHEADER,array(
’Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*’,
’Referer: http://www.myspace.com/index.cfm?fuseaction=splash’,
’Accept-Language: zh-cn’,
’Content-Type: application/x-www-form-urlencoded’,
//’Accept-Encoding: gzip,deflate’,
’User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1)’,
’Host: login.myspace.com’,
’Content-Length: 169′,
’Connection: Keep-Alive’,
’Cache-Control: no-cache’
));
?>
CURLOPT_POST与CURLOPT_POSTFIELDS:模拟POST的句子
例子:
<?php
curl_setopt($login,CURLOPT_POST,1);
curl_setopt($login, CURLOPT_POSTFIELDS, ‘email=’.$username.’&password=’.$password.’&Remember=Remember& ctl00%24Main%24SplashDisplay%24login%24loginbutton.x=43&ctl00%24Main% 24SplashDisplay%24login%24loginbutton.y=12′);//在这个里面要用urlencode来进行编码
?>
3.网页嗅探:
嗅探器是分析网页结构的重要工具,一般使用:
httpwatch professional版本,建议4以上,装上后,会在IE的工具栏中添加嗅探器图标,爬取网页的时候,使用点击此图标就可以嗅探网页了。
还有一个米老鼠头像的httpsniffer,此工具可以作为辅助,可以看到你的程序里面发送的数据是否正确等等。帮助调试之用.
<?php