php curl函数采集网页程序代码
curl来抓取网页内容是一个性能比较好的函数了,我们通常会使用它来快速模仿用户去访问我们要抓取的网页了,下面看一个例子有兴趣的朋友可进入参考。
早上想写了一个抓取是京东618魅族专题页的抓取,然后想着自动下单购买,尼玛,算了,太多了,写到判断是否开始了,商品价格进行了变化,后边工程量有点大就懒的写了,如果要完善的话就需要写模拟登陆(这个不难)加入购物车,下单,下单的时候判断一下价格,如果价格个官方优惠价格相同就下单,不同就接着去抓。算了,懒的写了。下边是部分代码
<?php
$cookie_file = dirname(__FILE__) . "/jd.cookie";
//专题首页url
$indexurl = 'http://sale.jd.com/act/BOxFsKPGNZwpet4.html';
//获取专题页到产品详情的地址
$indexstr = get($indexurl);
//var_dump($indexstr);exit;
preg_match_all('/<area shape="rect" coords="802,199,941,244" href="(.*?)"/is', $indexstr, $data);
$tmp = pathinfo($data[1][0]);
$pinfo['id'] = $tmp['filename'];
$pinfo['url'] = $data[1][0];
unset($tmp, $data);
$pinfo = getPrice($pinfo['id']);
if ($pinfo['mainproduct']['price'] == 1799) {
addcar();
} else {
echo "还没有开始抢购";
}
function get($url, $flag = true) {
global $cookie_file;
$headerArray = array(
"content-type: application/x-www-form-urlencoded;charset=UTF-8",
);
//echo $cookie_file;exit;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, '"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0"');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); //设置头信息
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
$return = curl_exec($ch);
curl_close($ch);
if ($flag) $return = gzdecode($return);
return $return;
}
function getPrice($id) {
$priceUrl = "http://rs.jd.com/accessorie/newServiceWhite.jsonp?sku=" . $id;
$data = json_decode(get($priceUrl, false) , true);
return $data;
}
function addcar() {
global $pinfo;
$addurl = "http://gate.jd.com/InitCart.aspx?pid=" . $pinfo['mainproduct']['sku'] . "&pcount=1&ptype=1";
echo get($addurl, false);
}
?>php 在curl抓取的时候出现乱码
用站长工具查看我们抓取的网而不是使用了gzip压缩了,如果有返回"Accept-Encoding:gzip, deflate" 就是打开了gzip了,我们只要如下操作
<?php
$res = curl_exec($ch1);
if (!empty($res)) { //save capcha
echo gzdecode($res);
}
?>GBK或者UTF8汉字之类的乱码
mb_convert_encoding($str, 'utf-8', 'GBK,UTF-8,ASCII');就行了
我们设置页面为GBK兼容GB2312,GB2312是GBK的子集,所有GB2312编码的用GBK都能正确解出来
教程网址:http://www.phprm.com/code/62770.html
欢迎收藏∩_∩但请保留本文链接。