首先要安装ScrapySharp和HtmlAgilityPack,NuGet里面安装就可以了。
搜狗搜索2020年首探火星,打开开发者工具,得到以下界面
在这里插入图片描述
之后是第一条链接的页面:
在这里插入图片描述
此次完成的就是使用代码直接完成搜索引擎的第一条链接的读取。
下面附上C#代码:

using System;
using System.Collections.Generic;
using ScrapySharp.Network;
using ScrapySharp.Extensions;
using HtmlAgilityPack;

namespace ExtractBaiduPage
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri uri = new Uri("https://www.sogou.com/web?query=2020%E5%B9%B4%E9%A6%96%E6%8E%A2%E7%81%AB%E6%98%9F&_asf=www.sogou.com&_ast=&w=01015002&p=40040108&ie=utf8&from=index-nologin&s_from=index&oq=&ri=0&sourceid=sugg&suguuid=&sut=17893&sst0=1562497060595&lkt=0%2C0%2C0&sugsuv=1562497028320274&sugtime=1562497060595&pid=sogou-wsse-af5baf594e9197b4-0001");
            ScrapingBrowser browser1 = new ScrapingBrowser ();
            string html1 = browser1.DownloadString(uri) ;
            HtmlDocument dc = new HtmlDocument();

            try {
                dc.LoadHtml(html1);
                HtmlNode htmlNode = dc.DocumentNode;
                var href = htmlNode.CssSelect("h3.vrTitle").CssSelect("a");
                List<string> links=new List<string> ();
                
                foreach (var node in href)
                {
                    string tmpStr = (string)node.Attributes["href"].Value;
                    links.Add(tmpStr);
                }
                string firstLink = "https://www.sogou.com" + links[0];//读取出来的东西,需要加上前缀才能使用

                Uri nUri = new Uri(firstLink);//这个str参数里面必须有http之类的东西
                
                string html2 = browser1.DownloadString(nUri);
                dc.LoadHtml(html2);//搜狗这里得到的数据不能用,必须再次抓取数据,应该就是反爬机制吧

                string scondLink = html2.Substring(html2.IndexOf('(')+2, (html2.IndexOf(')')- html2.IndexOf('('))-3) ;//抓取需要的数据,根据具体情况调整
                

                 string html3 = browser1.DownloadString(new Uri(scondLink));
                 dc.LoadHtml(html3);
               
                htmlNode = dc.DocumentNode;
                href = htmlNode.CssSelect("title");//抓取该页标题
                foreach (var item in href)
                {
                    Console.WriteLine(item.InnerText);
                }
                Console.ReadKey();
            }
            catch
            {
                Console.WriteLine("失败");
                Console.ReadKey();
                return;
            }
           
            
        }
    }
}

Logo

加入社区!打开量化的大门,首批课程上线啦!

更多推荐