這幾天想做用現在比較流行的HtmlAgilityPack重寫下采集的功能,看了一些HtmlAgilityPack 的介紹,感覺非常好用,還內置了htmlWeb用來http請求。但是發現有的開啓了gzip壓縮的網頁請求時會報錯。
原來的代碼如下:
1 2 |
HtmlWeb webClient = new HtmlWeb(); HtmlDocument doc = webClient.Load(this.getUrl()); |
報錯信息爲“gzip”不是受支持的編碼名。
在谷歌上搜索了半天,終於找到解決方案,而且不必更換HttpRequest或WebClient進行請求。同時還可以用此方法設置cookie,render僞裝等等。。。
解決後代碼如下:
HtmlAgilityPack.HtmlWeb.PreRequestHandler handler = delegate(HttpWebRequest request)
{
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.CookieContainer = new System.Net.CookieContainer();
return true;
};
webClient.PreRequest += handler;
HtmlDocument doc = webClient.Load(this.getUrl());
更多參考代碼:
string url = "https://kaijiang.500.com/qxc.shtml";
HtmlWeb web = new HtmlWeb();
web.PreRequest += delegate (HttpWebRequest request)
{
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.CookieContainer = new System.Net.CookieContainer();
return true;
};
HtmlDocument doc = web.Load(url);
HtmlNode table = doc.DocumentNode.SelectSingleNode("/html/body/div[5]/div[3]/div[2]/div[1]/div[2]/table[1]");
table = HtmlNode.CreateNode(table.OuterHtml);
HtmlNode strong = table.SelectSingleNode("//strong");
if (strong == null)
throw new Exception("獲取期數失敗,位置strong");
string timeStr = strong.InnerText;
timeStr = Regex.Replace(timeStr, @"[^0-9]+", "");
HtmlNode ul = table.SelectSingleNode("//ul");
if (ul == null)
throw new Exception("獲取開獎記錄失敗,位置ul");
string val = ul.InnerText;
//獲取字符串中的數字
val = Regex.Replace(val, @"[^0-9]+", "");
更多:
C# HTML解析工具HtmlAgilityPack XPath 模糊查詢not()函數和contains()函數