2024-04-12 分類(lèi): 網(wǎng)站建設(shè)
爬蟲(chóng)作為時(shí)下最熱門(mén)的一項(xiàng)話(huà)題。
在爬蟲(chóng)技術(shù)上,python占據(jù)了大半壁江山。那.Net家族是否也能實(shí)現(xiàn)爬蟲(chóng)呢?答案是肯定的。
c 可能還算比較熱門(mén),但vb.net在國(guó)內(nèi)的飯碗全被c 搶走了。但是就7月的編程排行榜來(lái)看,世界排名還不差,僅比c 低了0.3%,遙遙領(lǐng)先JS和PHP。
接下來(lái),我們重拾.Net家族的兩位元老:c與vb.net,手把手教你寫(xiě)第一個(gè)出色的爬蟲(chóng)!這篇文章適合有一定基礎(chǔ)掌,握基本語(yǔ)法的朋友參考。我在此拋磚引玉。
網(wǎng)頁(yè)爬蟲(chóng)何為爬蟲(chóng)?簡(jiǎn)單地說(shuō)就是一種抓取某個(gè)網(wǎng)頁(yè)HTML代碼的一項(xiàng)技術(shù)。通常用于數(shù)據(jù)接口交互、采集信息等。獲取網(wǎng)頁(yè)源碼只是第一步,還要從獲取的數(shù)據(jù)中提取到有用的數(shù)據(jù),比如網(wǎng)頁(yè)標(biāo)題、網(wǎng)頁(yè)內(nèi)容、圖片等。
總結(jié)一下,其實(shí)爬蟲(chóng)部分就只有兩個(gè)步驟:獲取網(wǎng)頁(yè)源代碼>分析并取得有用數(shù)據(jù)
下面介紹三種不同的爬取方式,分別適用于不同場(chǎng)景。
正常爬取網(wǎng)頁(yè)源代碼大部分瀏覽器在打開(kāi)某個(gè)網(wǎng)頁(yè)后,右鍵都有查看源代碼這一項(xiàng)。在這一大串的HTML代碼里面,可以看到網(wǎng)頁(yè)上顯示的網(wǎng)頁(yè)標(biāo)題、內(nèi)容數(shù)據(jù)、圖片內(nèi)容等等。
在Net下,有多種方式來(lái)獲取網(wǎng)頁(yè)源碼。都是通過(guò)模擬發(fā)送http協(xié)議來(lái)實(shí)現(xiàn)的。
一般情況下,可以使用NET及系統(tǒng)自帶的HttpXML對(duì)象、WebClient對(duì)象和HttpWebRequest對(duì)象來(lái)實(shí)現(xiàn)。當(dāng)然,有能力的可以采用純Socket來(lái)實(shí)現(xiàn)。
這里推薦采用HttpWebRequest方式。
以下是c代碼HttpWebRequest方式獲取源代碼的函數(shù):
publicstringGetHtmlStr(stringurl){try{ Uri uri =newUri(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.UserAgent ="User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"; request.Accept ="*/*"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader sr =newStreamReader(s, System.Text.Encoding.GetEncoding("utf-8"));stringhtml = sr.ReadToEnd(); s.Close(); response.Close();returnhtml; }catch(Exception ex) {return"/error/"; } }以及咱說(shuō)好的vb.net代碼
Public Function GetHtmlStr(ByVal url As String) As String Try Dim uri As Uri = New Uri(url) Dim request As HttpWebRequest = CType(WebRequest.Create(uri), HttpWebRequest) request.UserAgent ="User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"request.Accept ="*/*"Dim responseAsHttpWebResponse = CType(request.GetResponse(), HttpWebResponse) Dim sAsStream = response.GetResponseStream() Dim srAsStreamReader =NewStreamReader(s, System.Text.Encoding.GetEncoding("utf-8")) Dim htmlAsString= sr.ReadToEnd() s.Close() response.Close()Returnhtml Catch exAsExceptionReturn"/error/"EndTryEndFunction這個(gè)獲取網(wǎng)頁(yè)源碼的函數(shù)以及封裝好,調(diào)用非常簡(jiǎn)單:
GetHtmlStr("網(wǎng)址")如果發(fā)生錯(cuò)誤,返回字符串/error/。這里,特別注意代碼中的utf-8編碼。編碼錯(cuò)誤會(huì)造成獲取到亂碼,還有命名空間的引用。
ImportsSystem.Net.SecurityImportsSystem.Security.AuthenticationImportsSystem.Security.Cryptography.X509CertificatesPublicFunctionCheckValidationResult(ByValsenderAsObject,ByValcertificateAsX509Certificate,ByValchainAsX509Chain,ByValerrorsAsSslPolicyErrors)AsBooleanReturnTrueEndFunction并在以上的GetHTMLStr函數(shù)中HttpWebRequest = xxx 添加以下代碼即可
ServicePointManager.ServerCertificateValidationCallback= New System.Net.Security.RemoteCertificateValidationCallback(AddressOf CheckValidationResult)附帶Cookie方式GET和POST爬取vb.net代碼:
Public Function GetHtmlStr(ByVal url As String, cookies As String) As String Try Dim ck As New CookieContainer ck.SetCookies(New Uri(url), cookies) Dim uri As Uri = New Uri(url) Dim request As HttpWebRequest = CType(WebRequest.Create(uri), HttpWebRequest) request.UserAgent ="User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"request.Accept ="*/*"request.CookieContainer = ck Dim responseAsHttpWebResponse = CType(request.GetResponse(), HttpWebResponse) Dim sAsStream = response.GetResponseStream() Dim srAsStreamReader =NewStreamReader(s, System.Text.Encoding.GetEncoding("utf-8")) Dim htmlAsString= sr.ReadToEnd() s.Close() response.Close()Returnhtml Catch exAsExceptionReturn"/error/"EndTryEndFunctionc代碼:
publicstringGetHtmlStr(stringurl,stringcookies){try{ CookieContainer ck =newCookieContainer(); ck.SetCookies(newUri(url), cookies); Uri uri =newUri(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.UserAgent ="User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"; request.Accept ="*/*"; request.CookieContainer = ck; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader sr =newStreamReader(s, System.Text.Encoding.GetEncoding("utf-8"));stringhtml = sr.ReadToEnd(); s.Close(); response.Close();returnhtml; }catch(Exception ex) {return"/error/"; }}以上代碼不難看出,其實(shí)就是在普通爬取版本上增加了cookie對(duì)象的引入。GetHtmlStr函數(shù)的Cookie參數(shù)格式為:cookie名=值,多個(gè)用逗號(hào)隔開(kāi),如:name=123,pass=123
對(duì)了,還有post方法的vb.net版本:
PrivateFunctionHttpPost(Url As String, postDataStr As String)AsStringDimrequestAsHttpWebRequest=DirectCast(WebRequest.Create(Url), HttpWebRequest)request.Method= "POST"request.ContentType= "application/x-www-form-urlencoded"request.UserAgent= "Mozilla/5.0(Windows NT10.0; WOW64)AppleWebKit/537.36(KHTML, like Gecko)Chrome/59.0.3071.115Safari/537.36"request.ContentLength=Encoding.UTF8.GetByteCount(postDataStr)DimmyRequestStreamAsStream=request.GetRequestStream()DimmyStreamWriterAsNewStreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"))myStreamWriter.Write(postDataStr)myStreamWriter.Close()DimresponseAsHttpWebResponse=DirectCast(request.GetResponse(), HttpWebResponse)DimmyResponseStreamAsStream=response.GetResponseStream()DimmyStreamReaderAsNewStreamReader(myResponseStream, Encoding.GetEncoding("gb2312"))DimretStringAsString=myStreamReader.ReadToEnd()myStreamReader.Close()myResponseStream.Close()ReturnretStringEndFunctionc版本:
privatestringHttpPost(stringUrl,stringpostDataStr){HttpWebRequest request;WebRequest.Create(Url);HttpWebRequest;request.Method ="POST";request.ContentType ="application/x-www-form-urlencoded";request.UserAgent ="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safa"+"ri/537.36";request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);Stream myRequestStream = request.GetRequestStream();StreamWriter myStreamWriter =newStreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));myStreamWriter.Write(postDataStr);myStreamWriter.Close();HttpWebResponse response;request.GetResponse();HttpWebResponse;Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader =newStreamReader(myResponseStream, Encoding.GetEncoding("gb2312"));stringretString = myStreamReader.ReadToEnd();myStreamReader.Close();myResponseStream.Close();returnretString;}留個(gè)小作業(yè),這里的HttpPost函數(shù)cookie參數(shù)部分,可以參考上面的帶cookie的Get方案自行添加。
瀏覽器爬取有一些網(wǎng)頁(yè),前端顯示的內(nèi)容是由后端JS動(dòng)態(tài)生成,以上兩種獲取網(wǎng)頁(yè)的方式都無(wú)法正常獲取。那難道真的就沒(méi)有任何辦法了嗎?不見(jiàn)得。我們還可以利用Net自帶的IE控件webBrowser解釋網(wǎng)頁(yè)JS后再獲?。?/p>PublicSub WebBrowserOpenURL(WAsWebBrowser, SAsString)TryW.Navigate(S)While(W.ReadyState <> WebBrowserReadyState.Complete) Application.DoEvents() EndWhileCatchexAsExceptionEndTryEnd SubpublicvoidWebBrowserOpenURL(WebBrowser W,stringS){try{ W.Navigate(S);while((W.ReadyState != WebBrowserReadyState.Complete)) Application.DoEvents(); }catch(Exception ex) { }}
等到此自定義過(guò)程結(jié)束時(shí),再通過(guò)webBrowser1.DocumentText方法獲取控件中顯示的所有內(nèi)容。
當(dāng)然,如果條件允許,可以使用chromium來(lái)獲得更好的兼容性和性能。
其他以上三種不同的源碼爬取方式適合不同的場(chǎng)景。但是要分別注意以下三點(diǎn):
1)瀏覽器UA,即瀏覽器標(biāo)識(shí)。一些網(wǎng)頁(yè)需要移動(dòng)端才能正常顯示。
2)網(wǎng)頁(yè)編碼。編碼設(shè)置錯(cuò)誤會(huì)造成返回亂碼。
3)請(qǐng)遵守網(wǎng)站使用條款和相關(guān)法規(guī),勿胡亂爬取。
以上代碼支持Winform以及web后端編程。
本次限于篇幅,就簡(jiǎn)單介紹到這。下一期將介紹如何從爬取的HTML代碼中分析并獲取想要的數(shù)據(jù)。
非常感謝您讀完創(chuàng)新互聯(lián)的這篇文章:"c#與vb.net兩套代碼手把手教你寫(xiě).net網(wǎng)頁(yè)爬蟲(chóng)",僅為提供更多信息供用戶(hù)參考使用或?yàn)閷W(xué)習(xí)交流的方便。我們公司提供:網(wǎng)站建設(shè)、網(wǎng)站制作、官網(wǎng)建設(shè)、SEO優(yōu)化、小程序制作等服務(wù),歡迎聯(lián)系我們提供您的需求。
網(wǎng)站題目:c#與vb.net兩套代碼手把手教你寫(xiě).net網(wǎng)頁(yè)爬蟲(chóng)
網(wǎng)站URL:http://jinyejixie.com/news1/323401.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、網(wǎng)站導(dǎo)航、標(biāo)簽優(yōu)化、搜索引擎優(yōu)化、服務(wù)器托管、建站公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容