標籤:style http io os 使用 ar for 資料 art
在實際生活中,網路請求的應用極其常見,比如使用瀏覽器,程式中我們還要調用webservice。那麼瀏覽器是怎麼請求網路資源的呢?不用它可以自己請求不?
答案是可以的。
如果我們可以用自己的程式主動發起網路請求,那麼我們可以:類比提交資料,做一些簡單網頁遊戲的外掛,可以刷一些文章的訪問量,可以抓取網路上的資源……
廢話不我說,此文以使用Get方式對有道詞典網進行請求為核心,編寫了一個簡單的單詞查詢用戶端。Regex不太懂可以改為字串indexOf操作,或者對其自己做一下基本的瞭解和學習。
:
代碼:
using System;using System.Collections.Generic;using System.IO;using System.Net;using System.Text;using System.Text.RegularExpressions;namespace NetCapture{ /// <summary> /// base類。以後我們可能寫別的類似請求,通過繼承此類,可以省下一些代碼。 /// </summary> public abstract class GetScraperBase { //Regex的匹配模式 protected abstract string Pattern { get; } //如何過濾Regex匹配的結果 protected abstract Dictionary<string, string> FilterMatch(Match match); //抓取網頁上的內容 public Dictionary<string, string> Scrape(string url, WebProxy proxy = null) { var request = WebRequest.Create(url); if (proxy != null) { request.Proxy = proxy;//可能你在一些環境上不了網,得使用Proxy 伺服器 } var response = request.GetResponse(); var stream = response.GetResponseStream(); var responseReader = new StreamReader(stream); var content = responseReader.ReadToEnd(); var match = Regex.Match(content, Pattern, RegexOptions.IgnorePatternWhitespace); return FilterMatch(match); } } public class YouDaoScaper : GetScraperBase { protected override string Pattern { get { /* Target result in response: <div class="trans-container"> <ul> <li>n. 實驗;檢驗</li> <li>vt. 實驗;測試</li> <li>vi. 實驗;測試</li> <li>n. (Test)人名;(英)特斯特</li> </ul> * * there are two groups in this pattern, first is ‘<li>(?<content>.+)</li>[\r\n\s]*‘ * it‘s an unnamed group, it has four capture: * first is ‘<li>n. 實驗;檢驗</li>‘ and so on. * * another group is and named group ‘content‘ , it has four capture, in this sampe: * capture 1 is ‘n. 實驗;檢驗‘ and so on. */ return @"<div\sclass=""trans-container"">[\r\n\s]*<ul>[\r\n\s]*(<li>(?<content>.+)</li>[\r\n\s]*)*</ul>"; } } protected override Dictionary<string, string> FilterMatch(Match match) { var dict=new Dictionary<string, string>(); var content = ""; var group=match.Groups["content"]; if(group.Success) { foreach (Capture capture in group.Captures) { content += (capture.Value + "\n"); } } dict["content"]=content; return dict; } public string QueryWord(string word) { var url= "http://dict.youdao.com/search?q="+word; var dict = Scrape(url); return dict["content"]; } }}
[致初學者]類比Web請求——Get