using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Net;
using System.Web;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using System.IO;
namespace Pmars
{
class JingDong
{
//得到京东页面的编码格式
static Encoding encoding = Encoding.GetEncoding("gb2312");
//如果知道某件商品的ID,我们如何得到这件商品的价格
public static double GetPrice(string id)
{
double price = 0;
//第一种方式
//详细查看以前发过的图片识别的博客,利用识别京东价格图片的方法去获得商品的价格
price = GetPriceByImage(id);
//第二种方式
//虽然京东的价格被做成了图片的模式,但是,在购物车或者在结算的时候的价格不是图片的
//这样我们就可以想办法得到那里的价格就可以了
//实验证明,在获得购物车或者结算时的页面需要cookie
//那么,我们可以去下载另一个页面,之后记录cookie就可以解决问题了
//这里,定义一个类去继承WebClient,用来记录前后的cookie
price = GetPriceByCookie(id);
//第三种方式
//虽然京东在价格上做了很多的手脚,但是我们可以变相的采用其他的方式来处理
//比如,我们发现,京东有手机商城,这样,我们在手机商场上做了查看
//发现,手机商城根本就不用Cookie,而是直接下载页面就可以得到数据
//好吧,看下面的程序就可以了
price = GetPriceByMobile(id);
return price;
}
private static double GetPriceByImage(string id)
{
//京东的商品的Id是独一无二的,也就是说,每个Id标示了一件商品的内容页
//得到京东商品的下载页面
string downUrl = "http://www.360buy.com/product/"+id+".html";
//下载京东的商品内容页面,主要是为了下载图片
byte[] bytes = new WebClient().DownloadData(downUrl);
//通过编码得到页面的内容string,用HttpUtility.HtmlDecode解码
string content = HttpUtility.HtmlDecode(encoding.GetString(bytes));
//利用HtmlAgilityPack来加载分析Html页面内容
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(content);
//得到需要下载的价格图片节点
var imgNode = htmlDoc.DocumentNode.SelectSingleNode(@"//strong[@class='price']/img");
//得到需要下载的图片地址,需要用当前的页面地址去拼接一下,否则有可能是部分地址
string imgUrl = new Uri(new Uri(downUrl),imgNode.Attributes["src"].Value).AbsoluteUri;
//下载图片,放到Images文件夹下
//生成图片的地址,@"Images/" + 生成一个Guid以保证他们的名字都是不同的 + 图片的格式
string imgPath = @"Images/" + Guid.NewGuid().ToString().Replace("-", "") + imgUrl.Substring(imgUrl.LastIndexOf('.'));
//下载图片
new WebClient().DownloadFile(imgUrl, imgPath);
//分析图片,得到商品的价格
JingdongImage jdImage = new JingdongImage();
string priceStr = jdImage.GetPicNum(imgPath);
//定义一个匹配double的正则,从价格字符串中得到价格
//更简单的方法就是priceStr = priceStr.SubString(1);//去掉第一个¥字符
Regex doublePattern = new Regex(@"\d+(\.\d+)?", RegexOptions.Compiled);
string dbPrice = doublePattern.Match(priceStr).Value;
double price = 0;
if(double.TryParse(dbPrice,out price))
return price;
return 0;
}
private static double GetPriceByCookie(string id)
{
//京东的商品的Id是独一无二的,也就是说,每个Id标示了一件商品的内容页
//得到京东商品的加入购物车的链接,用程序来模仿人来将商品加入到购物车里面去
//加入购物车的链接
string goUrl = "http://jd2008.360buy.com/purchase/InitCart.aspx?p, '.');
}
}
}
相关文章: