1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using HtmlAgilityPack;
  9. namespace xpathGet
  10. {
  11. class Program
  12. {
  13. #region webclient创建
  14.  
  15. public class WebClientBD : System.Net.WebClient
  16. {
  17. protected override System.Net.WebRequest GetWebRequest(Uri address)
  18. {
  19.  
  20. HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
  21. request.AllowAutoRedirect = false;
  22. request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
  23. 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";
  24. return request;
  25. }
  26.  
  27. public WebResponse Response { get; private set; }
  28.  
  29. protected override WebResponse GetWebResponse(WebRequest request)
  30. {
  31. try
  32. {
  33. this.Response = base.GetWebResponse(request);
  34. }
  35. catch { }
  36. return this.Response;
  37.  
  38. }
  39.  
  40. }
  41. public static string lastUrl(string url)
  42. {
  43.  
  44. byte[] pageData = null;
  45.  
  46. string lasturl = null;
  47. string redirectLocal = null;
  48. try
  49. {
  50.  
  51. WebClientBD wc = new WebClientBD(); // 创建WebClient实例提供向URI 标识的资源发送数据和从URI 标识的资源接收数据
  52. wc.Credentials = CredentialCache.DefaultCredentials; // 获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。
  53. Encoding enc = Encoding.GetEncoding("utf-8"); // 如果是乱码就改成 utf-8 / GB2312
  54.  
  55. pageData = wc.DownloadData(url); // 从资源下载数据并返回字节数组。
  56.  
  57. if ((wc.Response as HttpWebResponse).StatusCode == HttpStatusCode.Found)
  58. {
  59. redirectLocal = ((wc.Response as HttpWebResponse).Headers["location"].StartsWith("http") == true ? string.Empty : "http://www.baidu.com") + (wc.Response as HttpWebResponse).Headers["location"];
  60. wc = new WebClientBD(); // 创建WebClient实例提供向URI 标识的资源发送数据和从URI 标识的资源接收数据
  61. wc.Credentials = CredentialCache.DefaultCredentials; // 获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。
  62. pageData = wc.DownloadData(redirectLocal);
  63. if ((wc.Response as HttpWebResponse).StatusCode == HttpStatusCode.Found)
  64. {
  65. lasturl = (wc.Response as HttpWebResponse).Headers["location"];
  66. }
  67. else if ((wc.Response as HttpWebResponse).StatusCode == HttpStatusCode.OK)
  68. {
  69. lasturl = redirectLocal;
  70. }
  71. }
  72. return lasturl;
  73.  
  74. }
  75. catch (Exception ex)
  76. {
  77.  
  78. return "error:" + ex.Message;
  79. }
  80. }
  81. #endregion
  82. public static string GetHtmlSource(string url)
  83. {
  84.  
  85. WebClientBD wc = new WebClientBD(); // 创建WebClient实例提供向URI 标识的资源发送数据和从URI 标识的资源接收数据
  86. wc.Credentials = CredentialCache.DefaultCredentials; // 获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据。
  87. Encoding enc = Encoding.GetEncoding("utf-8"); // 如果是乱码就改成 utf-8 / GB2312
  88. var pageData = wc.DownloadData(url); // 从资源下载数据并返回字节数组。
  89. return enc.GetString(pageData);
  90. }
  91.  
  92. static void Main(string[] args)
  93. {
  94. #region 翻页URL
  95. //http://www.baidu.com/s?wd={0}&pn={1}&oq={0}&ie=utf-8&usm=4
  96. #endregion
  97. string address = "http://www.baidu.com/s?wd={0}&pn={1}0&oq={0}&ie=utf-8&usm=4";
  98. string key = "代购";
  99. string htmlPageSource = string.Empty;
  100.  
  101. List<string> 其他最后的List = new List<string>();
  102. List<string> 广告最后的List = new List<string>();
  103.  
  104. string 广告 = "//div[@id='content_left']//div[contains(@id,'300')]{0}|//div[@id='content_left']//div[contains(@id,'400')]{1}";
  105. string 其他 = "//div[@id='content_left']//div[contains(@class,'c-container')]{0}";
  106. //取标题
  107.  
  108. for (int pnIndex = 0; pnIndex < 5; pnIndex++)
  109. {
  110. HtmlDocument doc = new HtmlDocument();
  111. List<string> 其他标题List = new List<string>();
  112. List<string> 其他标题链接List = new List<string>();
  113. List<string> 其他内容List = new List<string>();
  114. List<string> 其他citeList = new List<string>();
  115. List<string> 广告标题List = new List<string>();
  116. List<string> 广告标题链接List = new List<string>();
  117. List<string> 广告内容List = new List<string>();
  118. List<string> 广告citeList = new List<string>();
  119. htmlPageSource = GetHtmlSource(string.Format(address, key, pnIndex.ToString()));
  120. doc.LoadHtml(htmlPageSource);
  121. // doc.Load("D:\\rootInfo.html", Encoding.UTF8);
  122. HtmlNodeCollection 广告标题 = doc.DocumentNode.SelectNodes(string.Format(广告, "/div[1]/h3/a[1]", "/div[1]/h3/a[1]"));
  123. HtmlNodeCollection 广告标题链接 = doc.DocumentNode.SelectNodes(string.Format(广告, "/div[1]/h3/a[1]", "/div[1]/h3/a[1]"));
  124. HtmlNodeCollection 广告内容 = doc.DocumentNode.SelectNodes(string.Format(广告, "/div[2]", "/div[2]"));
  125. HtmlNodeCollection 广告cite = doc.DocumentNode.SelectNodes(string.Format(广告, "/div[2]//a/span[1]", "/div[3]/a/span"));
  126. HtmlNodeCollection 其他标题 = doc.DocumentNode.SelectNodes(string.Format(其他, "/h3/a[1]"));
  127. HtmlNodeCollection 其他标题链接 = doc.DocumentNode.SelectNodes(string.Format(其他, "/h3/a[1]"));
  128. 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文件存在限制指令')]"));
  129. HtmlNodeCollection 其他cite = doc.DocumentNode.SelectNodes(string.Format(其他, "//span[@class='c-showurl']") + "|" + string.Format(其他, "//a[@class='c-showurl']"));
  130. //分析每个结果都有一个标题,现在是最新相关信息的结果没有cite,判断哪个没有cite给其赋值“new info”
  131. //如果有最新相关信息的结果 ,假设标题有9个结果,则cite有8个。
  132. // 1.如果最新消息在最后一个此时标题的index=8,cite的index=8,最后一个标题index=9,但是cite的index是不存在的所以添加一个元素“new info。其他位置则插入元素
  133.  
  134. foreach (var item in 其他cite)
  135. {
  136. 其他citeList.Add(item.InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
  137. }
  138.  
  139. foreach (var item in 其他内容)
  140. {
  141. 其他内容List.Add(item.InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
  142.  
  143. }
  144.  
  145. for (int i = 0; i < 其他标题.Count; i++)
  146. {
  147. 其他标题List.Add(其他标题[i].InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
  148. 其他标题链接List.Add(其他标题链接[i].GetAttributeValue("href", "").Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
  149. }
  150.  
  151. if (其他标题List.Count != 其他citeList.Count)
  152. {
  153. if (其他标题[其他citeList.Count].InnerText.Contains("的最新相关信息"))
  154. {
  155. 其他citeList.Add("new info");
  156. }
  157. else
  158. {
  159.  
  160. for (int i = 0; i < 其他标题List.Count; i++)
  161. {
  162. if (其他标题List[i].Contains("的最新相关信息"))
  163. {
  164. 其他citeList.Insert(i, "new info");
  165. }
  166. }
  167. }
  168. }
  169. // List<string> 其他最后的List = new List<string>();
  170.  
  171. for (int j = 0; j < 其他标题List.Count; j++)
  172. {
  173. 其他最后的List.Add(其他标题List[j] + "|" + 其他标题链接List[j] + "|" + 其他内容List[j] + "|" + 其他citeList[j] + "\t");
  174. }
  175. 其他最后的List.Add(String.Format("以上为第{0}页搜索结果。", pnIndex + 1));
  176. string path = @"d:\\infolist_Page" + (pnIndex+1) + ".html";
  177. File.WriteAllText(path, htmlPageSource, Encoding.UTF8);
  178.  
  179. for (int i = 0; i < 广告标题.Count; i++)
  180. {
  181. 广告标题List.Add(广告标题[i].InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
  182. 广告内容List.Add(广告内容[i].InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
  183. 广告标题链接List.Add(广告标题链接[i].GetAttributeValue("href", "").Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
  184. 广告citeList.Add(广告cite[i].InnerText.Trim().Replace(" ", String.Empty).Replace("\n", string.Empty).Replace(" ", string.Empty));
  185. }
  186. for (int j = 0; j < 广告标题List.Count; j++)
  187. {
  188. 广告最后的List.Add(广告标题List[j] + "|" + 广告标题链接List[j] + "|" + 广告内容List[j] + "|" + 广告citeList[j] + "\t");
  189. }
  190. 广告最后的List.Add(String.Format("以上为第{0}页搜索结果。", pnIndex + 1));
  191. }
  192.  
  193. File.WriteAllLines(@"d:\\infolist.txt", 其他最后的List.ToArray(), Encoding.UTF8);
  194. File.WriteAllLines(@"d:\\infolist2.txt", 广告最后的List.ToArray(), Encoding.UTF8);
  195. }
  196. }
  197. }

  

C# 百度搜索结果xpath分析的更多相关文章

  1. PHP网络爬虫实践:抓取百度搜索结果,并分析数据结构

    百度的搜索引擎有反爬虫机制,我先直接用guzzle试试水.代码如下: <?php /** * Created by Benjiemin * Date: 2020/3/5 * Time: 14:5 ...

  2. python--selenium简单模拟百度搜索点击器

    python--selenium简单模拟百度搜索点击器 发布时间:2018-02-28 来源:网络 上传者:用户 关键字: selenium 模拟 简单 点击 搜索 百度 发表文章摘要:用途:简单模拟 ...

  3. Python:输入关键字进行百度搜索并爬取搜索结果

    学习自:手把手教你用Python爬取百度搜索结果并保存 - 云+社区 - 腾讯云 如何利用python模拟百度搜索,Python交流,技术交流区,鱼C论坛 指定关键字,对其进行百度搜索,保存搜索结果, ...

  4. Splinter学习--初探1,模拟百度搜索

    Splinter是以Selenium, PhantomJS 和 zope.testbrowser为基础构建的web自动化测试工具,基本原理同selenium 支持的浏览器包括:Chrome, Fire ...

  5. 利用python爬取海量疾病名称百度搜索词条目数的爬虫实现

    实验原因: 目前有一个医疗百科检索项目,该项目中对关键词进行检索后,返回的结果很多,可惜结果的排序很不好,影响用户体验.简单来说,搜索出来的所有符合疾病中,有可能是最不常见的疾病是排在第一个的,而最有 ...

  6. jsonp跨越请求百度搜索api 实现下拉列表提示

    题目来源: 最近在做百度IFE前端技术学院的题,然后有一题就是模拟百度搜索智能提示.题目是开源的,稍后给出地址. 因为博主没学过后端啊,欲哭无泪,所以不能实现后端模糊搜索,那如果前端ajax纯粹请求一 ...

  7. 百度搜索URL参数 搜索关键字

    http://www.baidu.com/s?wd=关键字 wd(Keyword):查询的关键词: http://www.baidu.com/s?wd=关键字&cl=3 cl(Class):搜 ...

  8. python爬取百度搜索结果ur汇总

    写了两篇之后,我觉得关于爬虫,重点还是分析过程 分析些什么呢: 1)首先明确自己要爬取的目标 比如这次我们需要爬取的是使用百度搜索之后所有出来的url结果 2)分析手动进行的获取目标的过程,以便以程序 ...

  9. 使用curl制作简易百度搜索

    这几天研究了一下php中的curl类库,做了一个简单的百度搜索,先上代码 <div style="width:200px;height:100px;"> <div ...

随机推荐

  1. 蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]

    题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...

  2. Windows10 版本说明 From wiki 20190104

    Windows版本说明 文字版本的: PC版本历史[编辑] 索引:       旧版本       旧版本,受支援       最新版本       最新预览版本 Version 1507(Windo ...

  3. 常用OLAP引擎

    l  presto Presto是Facebook开发的分布式大数据SQL查询引擎,专门进行快速数据分析. 特点: 可以将多个数据源的数据进行合并,可以跨越整个组织进行分析. 直接从HDFS读取数据, ...

  4. hdu 5274 Dylans loves tree (树链剖分 + 线段树 异或)

    Dylans loves tree Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Othe ...

  5. IntelliJ IDEA2017 修改缓存文件的路径

    IDEA的缓存文件夹.IntelliJIdea2017.1,存放着IDEA的破解密码,各个项目的缓存,默认是在C盘的用户目录下,目前有1.5G大小.现在想要把它从C盘移出. 在IDEA的安装路径下中, ...

  6. MT【179】最大最小老问题

    求$\max\{x^2+2y+20,y^2-6x+12\}$的最小值______ 提示:$4t\ge 3(x^2+2y+20)+y^2-6x+12=3(x-1)^2+(y+3)^2+60\ge 60, ...

  7. MT【101】分配问题举例若干

    先拿MT[100]的图表镇楼. 举几个例子: [1]52张纸牌分发给4人,每人13张,问每人手中有一张小2的概率? 分析:第一步每人分一张小2,有4!种,然后48张牌平均分成4组有$\frac{48! ...

  8. 使用Metasploit绕过UAC的多种方法

      一.用户帐户控制(UAC)简介 在本文中,我们将简要介绍一下用户帐户控制,即UAC.我们还将研究它如何潜在地保护免受恶意软件的攻击并忽略UAC提示可能给系统带来的一些问题. 1.什么是用户帐户控制 ...

  9. VS2017企业版本(安装包+key)+ .NET Reflector 9.0

    关于VS2017安装的一点扩充说明(15.5):http://www.cnblogs.com/dunitian/p/8051985.html Key激活无需断网 Visual Studio 2017 ...

  10. Python GIL全局解释器锁

    '''在python原始解释器Cpython中存在GIL(Global Interpreter Lock,全局解释器锁),因此在执行Python代码 时,会产生互斥锁来限制线程对共享资源的访问,指导接 ...