C# 百度搜索结果xpath分析

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);
        }
    }
}

  

时间: 2024-08-02 09:11:43

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

浏览器点击百度搜索结果之后,原搜索页面出现重定向乱码不断刷新问题的分析和解决

一.出现问题的环境: 1. ubuntu 14.04 LTS 2. 浏览器:Firefox 45.0.1 Mozilla Firefox for Ubuntu 二.出现问题的具体情况: 1. 用百度(其他搜索引擎没有出现类似问题)进行搜索,点击搜索结果后出现的新网页正常,但是原来的搜索结果出现了问题,如图所示 图一 图二      原来的搜索结果进行了自动刷新,并显示了乱码的搜索结果 每次点击搜索结果后,都要后退好麻烦,不能忍... 2.由于尝试了其他的搜索引擎没有出现问题,所以分析问题应该和百

百度搜索分析

百度搜索是全球最大的中文搜索引擎,是一款非常实用的搜索工具. 一.用户界面 百度搜索的用户界面比较简洁,不需要使用花哨的界面,给用户一种一目了然的感觉. 二.记住用户选择 百度搜索具有记忆用户搜索的功能,可以方便用户查询到之前查询的东西. 三.短期刺激 百度搜索具有分类搜索的功能,有网页.新闻.音乐等功能的搜索,比较能快速找到需要的东西. 四.长期使用的好处/坏处 好处:记忆用户之前的查询,比较方便,快捷. 坏处:搜索首页广告较多,不能使用户直观的获得答案. 五.不要让用户犯简单的错误 百度搜索

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

题目来源: 最近在做百度IFE前端技术学院的题,然后有一题就是模拟百度搜索智能提示.题目是开源的,稍后给出地址. 因为博主没学过后端啊,欲哭无泪,所以不能实现后端模糊搜索,那如果前端ajax纯粹请求一份同样的数据,效果就不好. 机智的博主直接把百度搜索api借来一下. 直接从开发者工具,监控网络,找到请求地址. 百度api: 我把api缩减了一下,删除了大部分暂时用不上的参数. https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=abc

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

写了两篇之后,我觉得关于爬虫,重点还是分析过程 分析些什么呢: 1)首先明确自己要爬取的目标 比如这次我们需要爬取的是使用百度搜索之后所有出来的url结果 2)分析手动进行的获取目标的过程,以便以程序实现 比如百度,我们先进行输入关键词搜索,然后百度反馈给我们搜索结果页,我们再一个个进行点击查询 3)思考程序如何实现,并克服实现中的具体困难 那么我们就先按上面的步骤来,我们首先认识到所搜引擎,提供一个搜索框,让用户进行输入,然后点击执行 我们可以先模拟进行搜索,发现点击搜索之后的完整url中有一

百度搜索关键词上线大家快点踊跃使用吧

近日,百度站长平台对百度搜索关键词工具进行了全面的升级,统计数据越来越精细,指标描述也越来越亲民.对于广大SEOer来说,长期总结观察这些百度数据,对于更好的了解其站点优化情况,对于制定其未来的关键词优化方案都大有裨益.可以说,新的数据数量级别和指标描述的改变,也标志着百度正逐步将加快其完善算法的步伐,大家有望在未来享受更公正的优化排名规则. 这次,百度主要通过热门关键词和热门页面来描述网站的受欢迎状况.注意,所谓的热门关键词和热门页面,是针对您自己的网站而言的,不具有绝对的统一性.您网站通过哪

AJAX实现分页--模拟百度搜索分页

第一部分:效果与分析 1.百度分页组件: 2.自己实现的分页: 3.分析: 百度搜索分页,如果总页数大于10,用户最多只能看到10页内容,不足10页显示全部,当点击下一页时,数字页标向前移动一个单位,当点击上一页时向后移动一个单位. 第二部分:后台实现: 1.实现思路: 后台的处理思想是这样的,通过AJAX向后台发送请求,携带一个分页对象PageBean传过去,查询完毕后返回一个新的PageBean对象. 前台传入的PageBean对象参数: 属性 名称 是否必须 默认值 pageSize 每页

百度搜索词&amp;淘宝搜索词 接口实现

百度和淘宝并没有正式的提供一个公开API给我们用,但是经过分析他们的源代码,还是找到了解决方法. /*baidu&taobao callback*/ function dachie(d) { if (d.s) return d.s else { return d.result.map(function(item) { return item[0] }); } }; 以上是我分析了他们的数据结构做的一个callback函数. 首先是百度: $.get("http://suggestion.

人机交互-----百度搜索产品评价

*用户界面: 1功能部件: 首页显示 搜索栏,相关产品登陆设置,各版块的推荐信息等. 搜索界面会有分类搜索,广告推荐. 1.1从用户角度考虑 用户需求: A需要百度相关产品如百度地图->点击进入,B需要搜索问题->在搜索栏输入自己的问题 登陆:选择登陆后不愿意每次操作都登陆 推荐信息推送:不愿意看见不关注的问题 设置:通过"搜索设置,高级设置,首页设置"对产品做不同使用要求 设计人员: 登陆:可选择记住密码 推荐消息推送:根据用户浏览记录分析或者实时热点进行推送,减少浏览记

5月5日 百度搜索技巧

1.“”——精确匹配 如果输入的查询词很长,百度在经过分析后,给出的搜索结果中的查询词,可能是拆分的.如果您对这种情况不满意,可以尝试让百度不拆分查询词.给查询词加上双引号,就可以达到这种效果.如:“上海大学”,搜索结果中的上海大学四个字就不会是分开的. 2.(-)——消除无关性 逻辑“非”的操作,用于排除无关信息,有利于缩小查询范围.百度支持"-"功能,用于有目的地删除某些无关网页,语法是"A -B".如:要搜寻关于"武侠小说",但不含&quo