[爬虫学习笔记]ScrapySharp简单封装为Requester

为了便于使用及日后的扩展,将Scrapy简单封装为了Requester,具体代码如下:

using System;
using System.Collections.Generic;
using Crawler.Common;

namespace Crawler.Protocol
{
    public class Requester
    {
        private Uri Url { get; set; }
        private Browser Browser { get; set; }

        public Requester(string url, Dictionary<string, string> headers = null, Browser browser = null)
        {
            var u = new Uri(url);
            //检测地址是域名还是IP地址,如果是域名,则使用DnsResolver解析为IP地址
            var leftPart = u.GetLeftPart(UriPartial.Authority).Replace(u.GetLeftPart(UriPartial.Scheme), "");
            //正则匹配是否为IP地址
            if (!RegexHelper.IsMatch(leftPart, @"\d+\.\d+\.\d+\.\d+\w"))
            {
                var dns = new DnsResolver(leftPart);
                if (dns.IsSuccess)
                    u = new Uri(url.Replace(leftPart, dns.Record.Address.ToString()));
            }
            Url = u;
            Browser = browser ?? new Browser();
            if (headers == null) return;
            foreach (var header in headers)
                Browser.Headers[header.Key] = header.Value;
        }



        public string GetHtml()
        {
            return Browser.DownloadString(Url);
        }

        public byte[] GetFile()
        {
            return Browser.NavigateToPage(Url).RawResponse.Body;
        }
    }
}

 

考虑到可能对ScrapyBrowser做一些扩展(例如增加对FTP等其他协议的支持),故新建了Browser类继承自ScrapyBrowser类:

using ScrapySharp.Network;

namespace Crawler.Protocol
{
    public class Browser : ScrapingBrowser
    {

    }
}

转载于:https://www.cnblogs.com/WayneShao/p/5866977.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SimpleBrowser是专门为自动化任务而设计的一个灵活而直观的浏览器引擎,内置.Net 4 framework。示例代码:class Program {     static void Main(string[] args)     {         var browser = new Browser();         try         {             // log the browser request/response data to files so we can interrogate them in case of an issue with our scraping             browser.RequestLogged  = OnBrowserRequestLogged;             browser.MessageLogged  = new Action<Browser, string>(OnBrowserMessageLogged);             // we'll fake the user agent for websites that alter their content for unrecognised browsers             browser.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10";             // browse to GitHub             browser.Navigate("http://github.com/");             if(LastRequestFailed(browser)) return; // always check the last request in case the page failed to load             // click the login link and click it             browser.Log("First we need to log in, so browse to the login page, fill in the login details and submit the form.");             var loginLink = browser.Find("a", FindBy.Text, "Login");             if(!loginLink.Exists)                 browser.Log("Can't find the login link! Perhaps the site is down for maintenance?");             else             {                 loginLink.Click();                 if(LastRequestFailed(browser)) return;                 // fill in the form and click the login button - the fields are easy to locate because they have ID attributes                 browser.Find("login_field").Value = "youremail@domain.com";                 browser.Find("password").Value = "yourpassword";                 browser.Find(ElementType.Button, "name", "commit").Click();                 if(LastRequestFailed(browser)) return;                 // see if the login succeeded - ContainsText() is very forgiving, so don't worry about whitespace, casing, html tags separating the text, etc.                 if(browser.ContainsText("Incorrect login or password"))                 {                     browser.Log("Login failed!", LogMessageType.Error);                 }                 else                 {                     // After logging in, we should check that the page contains elements that we recognise                     if(!browser.ContainsText("Your Repositories"))                         browser.Log("There wasn't the usual login failure message, but the text we normally expect isn't present on the page");                     else                     {                         browser.Log("Your News Feed:");                         // we can use simple jquery selectors, though advanced selectors are yet to be implemented                         foreach(var item in browser.Select("div.news .title"))                             browser.Log("* "   item.Value);                     }                 }             }         }         catch(Exception ex)         {             browser.Log(ex.Message, LogMessageType.Error);             browser.Log(ex.StackTrace, LogMessageType.StackTrace);         }         finally         {             var path = WriteFile("log-"   DateTime.UtcNow.Ticks   ".html", browser.RenderHtmlLogFile("SimpleBrowser Sample - Request Log"));             Process.Start(path);         }     }     static bool LastRequestFailed(Browser browser)     {         if(browser.LastWebException != null)         {             browser.Log("There was an error loading the page: "   browser.LastWebException.Message);             return true;         }         return false;     }     static void OnBrowserMessageLogged(Browser browser, string log)     {         Console.WriteLine(log);     }     static void OnBrowserRequestLogged(Browser req, HttpRequestLog log)     {         Console.WriteLine(" -> "   log.Method   " request to "   log.Url);         Console.WriteLine(" <- Response status code: "   log.ResponseCode);     }     static string WriteFile(string filename, string text)     {         var dir = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs"));         if(!dir.Exists) dir.Create();         var path = Path.Combine(dir.FullName, filename);         File.WriteAllText(path, text);         return path;     } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值