准备:
1.新建控制台项目
2.引用System.Drawing类库
3.安装HtmlAgilityPack 1.5.2.0
4.如果不会XPath语法的话,建议简单看下
代码:
static void Main(string[] args)
{
#region 爬虫测试
{
//此处为将要解析的URL,可设置为参数变量(我这里把URL写死了)
string html = HttpHelper.DownloadHtml(@"http://wyxa.googlefilm.com.cn/wenzhang/info_386854_w821759016~i5.html", Encoding.UTF8);
HtmlDocument doc = new HtmlDocument(); //由于本人要解析的网址,HTMl标签是动态生成的,所以不能将XPath表达式一次性写出,只能先解析出来非动态标签,再一步一步解析动态生成的标签.
doc.LoadHtml(html);//加载html(此时要解析的标签是非动态生成的,很好获取)
string pageNumberPath = @"//table[2]";
HtmlNode pageNumberNode = doc.DocumentNode.SelectSingleNode(pageNumberPath); //拿到以上获取的非动态标签之后,再解析里边的动态生成的标签,所以要再次LoadHtml一下
doc.LoadHtml(pageNumberNode.InnerHtml);
pageNumberPath = "//div[@id='div_text']";
pageNumberNode = doc.DocumentNode.SelectSingleNode(pageNumberPath); //同理,解析动态标签,再次LoadHtml
doc.LoadHtml(pageNumberNode.InnerHtml);
pageNumberPath = "//img";
HtmlNodeCollection pageNumberNodes = doc.DocumentNode.SelectNodes(pageNumberPath); //获取到需要的img标签集合后,遍历,获取src地址
foreach (var item in pageNumberNodes)
{
if (item.Attributes["data-src"] != null)
{
var imgSrc = item.Attributes["data-src"].Value; //控制台打印src地址
Console.WriteLine(imgSrc); //通过解析出来的src地址下载图片
DownloadPhotoFromUrl(imgSrc);
}
}
}
}
HttpHelper.DownloadHtml方法
public static string DownloadHtml(string url,Encoding encoding)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.Timeout = ;
HttpWebResponse httpWResp = (HttpWebResponse)myReq.GetResponse();
Stream myStream = httpWResp.GetResponseStream();
if (myStream != null)
{
StreamReader sr = new StreamReader(myStream, encoding);
return sr.ReadToEnd();
}
return "";
}
下载网络图片的方法:
/// <summary>
/// 从图片地址下载图片到本地磁盘
/// </summary>
/// <param name="Url">图片网址</param>
/// <returns></returns>
public static void DownloadPhotoFromUrl(string Url)
{
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(Url);
HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
if (webresponse.StatusCode == HttpStatusCode.OK)
{
System.Drawing.Image image = System.Drawing.Image.FromStream(webresponse.GetResponseStream());
//保存在本地文件夹
image.Save(@"D:\\images\"+DateTime.Now.ToString("yyyyMMddHHmmssff")+".jpg");
//释放资源
image.Dispose();
}
}
至此,功能完成.
以下为本人控制台打印结果:
图片下载截图:
本人菜鸟,只是为了记录学习中的小知识点,请大神勿喷~