php 抓取亚马逊中国产品数据-标题,价格,首图片

<?php
set_time_limit(0);
date_default_timezone_set("Asia/shanghai");
//自定义抓取图片地址
$url = 'http://www.amazon.cn/Apple-iPhone-5S-3G%E6%99%BA%E8%83%BD%E6%89%8B%E6%9C%BA/dp/B00FFVIPN8/ref=sr_1_1?ie=UTF8&qid=1395041969&sr=8-1&keywords=iphone5s';

$ip_arr = get_ips();
$ip = trim(get_rand_ip($ip_arr)); //随机ip
$content = get_content_by_url($url, $ip);

//获取标题
preg_match("/<span id=\"btAsinTitle\">[\s]*<span style=\"padding-left: 0\">[\s]*(.*?)[\s]*<\/span>/i", $content, $match_title);
if(isset($match_title[1]) && $match_title[1]){
	$title = $match_title[1];
	echo '标题为:' . $title . '<br />';
}else{
	echo '没有获取到标题,程序终止:';
	exit;
}
//获取价格
preg_match("/<b class=\"priceLarge\">¥[\s]*(.*?)<\/b>/i", $content, $match_price);
if(isset($match_title[1]) && $match_price[1]){
	$price = $match_price[1];
	echo '价格为:' . $price . '<br />';
}else{
	echo '没有获取到价格,程序终止:';
}
//获取图片
preg_match("/<div class=\"main-image-inner-wrapper\">[\s]*<img src=\"(.*)?\"/i", $content, $match_img);
if(isset($match_img[1]) && $match_img[1]){
	$img_url = $match_img[1];
	echo '图片地址为:' . $img_url . '<br />';
	echo "<img src='$img_url' width=300, height=300>";
}else{
	echo '没有获取图片地址,程序终止:';
	exit;
}

function get_rand_ip($ip_arr){
    if(empty($ip_arr)){
	    return false;
	}
	$ip_count = count($ip_arr);
	$rand_num = rand(0, $ip_count-1);
	return trim($ip_arr[$rand_num]);
}

function get_ips(){
    $fp = fopen('ip.txt', 'r+');
	$ip_arr = array();
	while($line=fgets($fp)){
	    array_push($ip_arr, $line);
	}
	fclose($fp);
	return $ip_arr;
}

function get_content_by_url($url, $ip = '127.0.0.1'){
	if(empty($url)){
		return;
	}
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.0)');
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); 
	if(!empty($ip)){
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:' . $ip, 'CLIENT-IP:' . $ip));  //构造IP
	}
	
	$content = curl_exec($ch);
	return $content;
}


抱歉,没找到上传附件的地方,ip.txt没上传。您可以百度下,有很多ip库,下载一个就能用,一行一个ip

转载于:https://my.oschina.net/u/568279/blog/209282

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值