如何在两个类中分隔这段代码?

时间:2013-09-04 02:52:00

标签: c# web-scraping

我想在c#中编写一个html scraper,它可以从我想要的页面获取链接或其他目标字符串。

我刚刚开始直接遇到问题:我不知道如何在类中分离代码,所以我可以使用不同的搜索引擎。

这是我目前的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Net;
using HtmlAgilityPack;

namespace Scraper.Components
{
    class Scraper
    {
        public Scraper()
        {
            WebClient client = new WebClient();
            client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)");

            HtmlDocument doc = new HtmlDocument();
            doc.Load(client.OpenRead("xxx"));

            HtmlNode rootNode = doc.DocumentNode;

            HtmlNodeCollection adNodes = rootNode.SelectNodes("//a[@class='ad-title']");

            foreach(HtmlNode adNode in adNodes) {
                Debug.WriteLine(
                    adNode.Attributes["href"].Value
                );
            }
        }
    }
}

我的意图是将client.Headers.Add下面的整个代码分成一个独立的类,所以我可以打电话给例如:

Scraper scraper = new Scraper(new GoogleSE('http://google.com/...'));

或类似的东西。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

到目前为止只是一个初学者的想法,但这样的事情应该有效。

这是the Strategy pattern的开头。您可能还想查看工厂模式以生成搜索引擎对象。

namespace Scraper.Components
{
    class Scraper
    {
        public Scraper(ISearchEngine engine)
        {
            WebClient client = new WebClient();
            client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)");
            engine.Search(client);
        }

    }
    class GoogleSE: ISearchEngine
    {
        public void Search(WebClient client){
            HtmlDocument doc = new HtmlDocument();
            doc.Load(client.OpenRead("http:\\google.com"));

            HtmlNode rootNode = doc.DocumentNode;

            HtmlNodeCollection adNodes = rootNode.SelectNodes("//a[@class='ad-title']");

            foreach(HtmlNode adNode in adNodes) {
                Debug.WriteLine(
                    adNode.Attributes["href"].Value
                );
            }
        }
    class BingSE: ISearchEngine
    {
        public void Search(WebClient client){
            HtmlDocument doc = new HtmlDocument();
            doc.Load(client.OpenRead("http:\\bing.com"));

            HtmlNode rootNode = doc.DocumentNode;

            HtmlNodeCollection adNodes = rootNode.SelectNodes("//a[@class='ad-title']");

            foreach(HtmlNode adNode in adNodes) {
                Debug.WriteLine(
                    adNode.Attributes["href"].Value
                );
            }
        }
    }

    Interface ISearchEngine{
        void Search();
    }
}