C# 百度搜索结果xpath分析

时间:2021-08-19 03:47:08

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using HtmlAgilityPack; namespace xpathGet { class Program { #region webclient创建 public class WebClientBD : System.Net.WebClient { protected override System.Net.WebRequest GetWebRequest(Uri address) { HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest; request.AllowAutoRedirect = false; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"; return request; } public WebResponse Response { get; private set; } protected override WebResponse GetWebResponse(WebRequest request) { try { this.Response = base.GetWebResponse(request); } catch { } return this.Response; } } public static string lastUrl(string url) { byte[] pageData = null; string lasturl = null; string redirectLocal = null; try { WebClientBD wc = new WebClientBD(); // 创建WebClient实例提供向URI 标识的资源发送数据和从URI 标识的资源接收数据 wc.Credentials = CredentialCache.DefaultCredentials; // 获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。 Encoding enc = Encoding.GetEncoding("utf-8"); // 如果是乱码就改成 utf-8 / GB2312 pageData = wc.DownloadData(url); // 从资源下载数据并返回字节数组。 if ((wc.Response as HttpWebResponse).StatusCode == HttpStatusCode.Found) { redirectLocal = ((wc.Response as HttpWebResponse).Headers["location"].StartsWith("http") == true ? string.Empty : "http://www.baidu.com") + (wc.Response as HttpWebResponse).Headers["location"]; wc = new WebClientBD(); // 创建WebClient实例提供向URI 标识的资源发送数据和从URI 标识的资源接收数据 wc.Credentials = CredentialCache.DefaultCredentials; // 获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。 pageData = wc.DownloadData(redirectLocal); if ((wc.Response as HttpWebResponse).StatusCode == HttpStatusCode.Found) { lasturl = (wc.Response as HttpWebResponse).Headers["location"]; } else if ((wc.Response as HttpWebResponse).StatusCode == HttpStatusCode.OK) { lasturl = redirectLocal; } } return lasturl; } catch (Exception ex) { return "error:" + ex.Message; } } #endregion public static string GetHtmlSource(string url) { WebClientBD wc = new WebClientBD(); // 创建WebClient实例提供向URI 标识的资源发送数据和从URI 标识的资源接收数据 wc.Credentials = CredentialCache.DefaultCredentials; // 获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。 Encoding enc = Encoding.GetEncoding("utf-8"); // 如果是乱码就改成 utf-8 / GB2312 var pageData = wc.DownloadData(url); // 从资源下载数据并返回字节数组。 return enc.GetString(pageData); } static void Main(string[] args) { #region 翻页URL //http://www.baidu.com/s?wd={0}&pn={1}&oq={0}&ie=utf-8&usm=4 #endregion string address = "http://www.baidu.com/s?wd={0}&pn={1}0&oq={0}&ie=utf-8&usm=4"; string key = "代购"; string htmlPageSource = string.Empty; List<string> 其他最后的List = new List<string>(); List<string> 广告最后的List = new List<string>(); string 广告 = "//div[@id=‘content_left‘]//div[contains(@id,‘300‘)]{0}|//div[@id=‘content_left‘]//div[contains(@id,‘400‘)]{1}"; string 其他 = "//div[@id=‘content_left‘]//div[contains(@class,‘c-container‘)]{0}"; //取标题 for (int pnIndex = 0; pnIndex < 5; pnIndex++) { HtmlDocument doc = new HtmlDocument(); List<string> 其他标题List = new List<string>(); List<string> 其他标题链接List = new List<string>(); List<string> 其他内容List = new List<string>(); List<string> 其他citeList = new List<string>(); List<string> 广告标题List = new List<string>(); List<string> 广告标题链接List = new List<string>(); List<string> 广告内容List = new List<string>(); List<string> 广告citeList = new List<string>(); htmlPageSource = GetHtmlSource(string.Format(address, key, pnIndex.ToString())); doc.LoadHtml(htmlPageSource); // doc.Load("D:\\rootInfo.html", Encoding.UTF8); HtmlNodeCollection 广告标题 = doc.DocumentNode.SelectNodes(string.Format(广告, "/div[1]/h3/a[1]", "/div[1]/h3/a[1]")); HtmlNodeCollection 广告标题链接 = doc.DocumentNode.SelectNodes(string.Format(广告, "/div[1]/h3/a[1]", "/div[1]/h3/a[1]")); HtmlNodeCollection 广告内容 = doc.DocumentNode.SelectNodes(string.Format(广告, "/div[2]", "/div[2]")); HtmlNodeCollection 广告cite = doc.DocumentNode.SelectNodes(string.Format(广告, "/div[2]//a/span[1]", "/div[3]/a/span")); HtmlNodeCollection 其他标题 = doc.DocumentNode.SelectNodes(string.Format(其他, "/h3/a[1]")); HtmlNodeCollection 其他标题链接 = doc.DocumentNode.SelectNodes(string.Format(其他, "/h3/a[1]")); HtmlNodeCollection 其他内容 = doc.DocumentNode.SelectNodes(string.Format(其他, "//div[@class=‘c-abstract‘]") + "|" + string.Format(其他, "//div[‘c-span18 c-span-last‘]/p[1]") + "|" + string.Format(其他, "//div[@class=‘c-offset‘]") + "|" + string.Format(其他, "//div[@class=‘op_dict_content‘]") + "|" + string.Format(其他, "//p[contains(text(),‘由于该网站的robots.txt文件存在限制指令‘)]")); HtmlNodeCollection 其他cite = doc.DocumentNode.SelectNodes(string.Format(其他, "//span[@class=‘c-showurl‘]") + "|" + string.Format(其他, "//a[@class=‘c-showurl‘]")); //分析每个结果都有一个标题,现在是最新相关信息的结果没有cite,判断哪个没有cite给其赋值“new info” //如果有最新相关信息的结果 ,假设标题有9个结果,,则cite有8个。 // 1.如果最新消息在最后一个此时标题的index=8,cite的index=8,最后一个标题index=9,但是cite的index是不存在的所以添加一个元素“new info。其他位置则插入元素 foreach (var item in 其他cite) { 其他citeList.Add(item.InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty)); } foreach (var item in 其他内容) { 其他内容List.Add(item.InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty)); } for (int i = 0; i < 其他标题.Count; i++) { 其他标题List.Add(其他标题[i].InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty)); 其他标题链接List.Add(其他标题链接[i].GetAttributeValue("href", "").Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty)); } if (其他标题List.Count != 其他citeList.Count) { if (其他标题[其他citeList.Count].InnerText.Contains("的最新相关信息")) { 其他citeList.Add("new info"); } else { for (int i = 0; i < 其他标题List.Count; i++) { if (其他标题List[i].Contains("的最新相关信息")) { 其他citeList.Insert(i, "new info"); } } } } // List<string> 其他最后的List = new List<string>(); for (int j = 0; j < 其他标题List.Count; j++) { 其他最后的List.Add(其他标题List[j] + "|" + 其他标题链接List[j] + "|" + 其他内容List[j] + "|" + 其他citeList[j] + "\t"); } 其他最后的List.Add(String.Format("以上为第{0}页搜索结果。", pnIndex + 1)); string path = @"d:\\infolist_Page" + (pnIndex+1) + ".html"; File.WriteAllText(path, htmlPageSource, Encoding.UTF8); for (int i = 0; i < 广告标题.Count; i++) { 广告标题List.Add(广告标题[i].InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty)); 广告内容List.Add(广告内容[i].InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty)); 广告标题链接List.Add(广告标题链接[i].GetAttributeValue("href", "").Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty)); 广告citeList.Add(广告cite[i].InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty)); } for (int j = 0; j < 广告标题List.Count; j++) { 广告最后的List.Add(广告标题List[j] + "|" + 广告标题链接List[j] + "|" + 广告内容List[j] + "|" + 广告citeList[j] + "\t"); } 广告最后的List.Add(String.Format("以上为第{0}页搜索结果。", pnIndex + 1)); } File.WriteAllLines(@"d:\\infolist.txt", 其他最后的List.ToArray(), Encoding.UTF8); File.WriteAllLines(@"d:\\infolist2.txt", 广告最后的List.ToArray(), Encoding.UTF8); } } }