自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

巧用IronPython做更靈活的網(wǎng)頁(yè)爬蟲(chóng)

開(kāi)發(fā) 后端
如果有了IronPython,可以把抓取和分析的邏輯做成Python腳本,如果對(duì)方頁(yè)面結(jié)構(gòu)變了,只需修改腳本就行了,不需重新編譯軟件,這樣可以用c#做交互和界面部分,用Python封裝預(yù)期經(jīng)常變化的部分。

由于各種原因,我們經(jīng)常需要去別的網(wǎng)站采集一些信息,.net下所有相關(guān)的技術(shù)都已經(jīng)非常成熟,用Webrequest抓取頁(yè)面,既支持自定義Reference頭,又支持cookie,解析頁(yè)面一般都是用正則,而且對(duì)方網(wǎng)站結(jié)構(gòu)一變,還得重新改代碼,重新編譯,發(fā)布。

如果有了IronPython,可以把抓取和分析的邏輯做成Python腳本,如果對(duì)方頁(yè)面結(jié)構(gòu)變了,只需修改腳本就行了,不需重新編譯軟件,這樣可以用c#做交互和界面部分,用Python封裝預(yù)期經(jīng)常變化的部分。

安裝好IronPython和vs.net 2010后,還需要下載一個(gè)SGMLReader(見(jiàn)參考鏈接),這個(gè)組件可以把格式不是很?chē)?yán)格的HTML轉(zhuǎn)換成格式良好的XML文件,甚至還能增加DTD的驗(yàn)證

我們以抓取百度貼吧頁(yè)面為例,新建一個(gè)Console項(xiàng)目,引用IronPython,Microsoft.Dynamic,Microsoft.Scripting,SgmlReaderDll這些組件,把SGMLReader里的Html.dtd復(fù)制到項(xiàng)目目錄下,如果沒(méi)有這個(gè),它會(huì)根據(jù)doctype去網(wǎng)絡(luò)上找dtd,然后新建baidu.py的文件,***在項(xiàng)目屬性的生成事件里寫(xiě)上如下代碼,把這兩個(gè)文件拷貝到目標(biāo)目錄里

  1. copy $(ProjectDir)\*.py $(TargetDir)  
  2. copy $(ProjectDir)\*.dtd $(TargetDir) 

在baidu.py里首先引用必要的.net程序集

  1. import clr, sys  
  2. clr.AddReference("SgmlReaderDll")  
  3. clr.AddReference("System.Xml"

完了導(dǎo)入我們需要的類

  1. from Sgml import *  
  2. from System.Net import *  
  3. from System.IO import TextReader,StreamReader  
  4. from System.Xml import *  
  5. from System.Text.UnicodeEncoding import UTF8 

利用SgmlReader寫(xiě)一個(gè)把html轉(zhuǎn)換成xml的函數(shù),注意SystemLiteral屬性必須設(shè)置,否則就會(huì)去網(wǎng)上找dtd了,浪費(fèi)時(shí)間

  1. def fromHtml(textReader):  
  2.     sgmlReader = SgmlReader()  
  3.     sgmlReader.SystemLiteral = "html.dtd" 
  4.     sgmlReader.WhitespaceHandling = WhitespaceHandling.All  
  5.     sgmlReader.CaseFolding = CaseFolding.ToLower  
  6.     sgmlReader.InputStream = textReader  
  7.       
  8.     doc = XmlDocument()  
  9.     doc.PreserveWhitespace = True 
  10.     doc.XmlResolver = None 
  11.     doc.Load(sgmlReader)  
  12.     return doc 

利用webrequest寫(xiě)一個(gè)支持cookie和網(wǎng)頁(yè)編碼的抓網(wǎng)頁(yè)方法

  1. def getWebData
  2. (url, method, data = None, cookie = None, encoding = "UTF-8"):  
  3.     req = WebRequest.Create(url)  
  4.     req.Method = method  
  5.       
  6.     if cookie != None:  
  7.         req.CookieContainer = cookie  
  8.       
  9.     if data != None:  
  10.         stream = req.GetRequestStream()  
  11.         stream.Write(data, 0, data.Length)  
  12.           
  13.     rsp = req.GetResponse()  
  14.     reader = StreamReader
  15. (rsp.GetResponseStream(), UTF8.GetEncoding(encoding))  
  16.     return reader 

寫(xiě)一個(gè)類來(lái)定義抓取結(jié)果,這個(gè)類不需要在c#項(xiàng)目里定義,到時(shí)候直接用c# 4.0的dynamic關(guān)鍵字就可以使用

  1. class Post:  
  2.     def __init__(self, hit, comments, title, link, author):  
  3.         self.hit = hit  
  4.         self.comments = comments  
  5.         self.title = title  
  6.         self.link = link  
  7.         self.author = author 

定義主要工作的類,__init__大概相當(dāng)于構(gòu)造函數(shù),我們傳入編碼參數(shù),并初始化cookie容器和解析結(jié)果,[]是python里的列表,大約相當(dāng)于c#的List

  1. class BaiDu:  
  2.     def __init__(self,encoding):  
  3.         self.cc = self.cc = CookieContainer()          
  4.         self.encoding = encoding  
  5.         self.posts = [] 

接下來(lái)定義抓取方法,調(diào)用getWebData抓網(wǎng)頁(yè),然后用fromHtml轉(zhuǎn)換成xml,剩下的就是xml操作,和.net里一樣,一看便知

  1. def getPosts(self, url):  
  2.         reader = getWebData
  3. (url, "GET"Noneself.cc, self.encoding)  
  4.         doc = fromHtml(reader)  
  5.           
  6.         trs = doc.SelectNodes
  7. ("html//table[@id='thread_list_table']/tbody/tr")  
  8.         self.parsePosts(trs)  
  9.       
  10.     def parsePosts(self, trs):  
  11.         for tr in trs:              
  12.             tds = tr.SelectNodes("td")  
  13.             hit = tds[0].InnerText  
  14.             comments = tds[1].InnerText  
  15.             title = tds[2].ChildNodes[1].InnerText  
  16.             link = tds[2].ChildNodes[1].Attributes["href"]  
  17.             author = tds[3].InnerText  
  18.               
  19.             post = Post(hit, comments, title, link, author)  
  20.             self.posts.append(post) 

c#代碼要?jiǎng)?chuàng)建一個(gè)腳本運(yùn)行環(huán)境,設(shè)置允許調(diào)試,然后執(zhí)行baidu.py,***創(chuàng)建一個(gè)Baidu的類的實(shí)例,并用dynamic關(guān)鍵字引用這個(gè)實(shí)例

  1. Dictionary options = new Dictionary();  
  2. options["Debug"] = true;  
  3. ScriptEngine engine = Python.CreateEngine(options);  
  4. ScriptScope scope = engine.ExecuteFile("baidu.py");  
  5. dynamic baidu = engine.Operations.Invoke(scope.GetVariable("BaiDu"), "GBK"); 

接下來(lái)調(diào)用BaiDu這個(gè)python類的方法獲取網(wǎng)頁(yè)抓取結(jié)果,然后輸出就可以了
 

  1. baidu.getPosts("http://tieba.baidu.com/f?kw=seo");  
  2.             dynamic posts = baidu.posts;  
  3.             foreach (dynamic post in posts)  
  4.             {  
  5.                 Console.WriteLine("{0}   
  6. (回復(fù)數(shù):{1})(點(diǎn)擊數(shù):{2})[作者:{3}]",  
  7.                     post.title,  
  8.                     post.comments,  
  9.                     post.hit,  
  10.                     post.author);  
  11.             } 

原文鏈接:http://www.cnblogs.com/onlytiancai/archive/2011/02/22/1960859.html

【編輯推薦】

  1. Python 3.2發(fā)布 改進(jìn)調(diào)試器PDB
  2. 淺談Python Web的五大框架
  3. 一個(gè)Python程序員的進(jìn)化
  4. 年度黑馬Python 自省指南
  5. 學(xué)習(xí)python處理python編碼
責(zé)任編輯:陳貽新 來(lái)源: 胡浩的博客
相關(guān)推薦

2011-02-22 10:00:38

.NETc#IronPython

2009-05-18 09:12:00

ASON自動(dòng)交換光網(wǎng)絡(luò)

2023-06-06 19:24:06

KubernetesSpark

2009-06-03 09:08:20

ScalaJava類型

2020-09-14 09:33:02

網(wǎng)絡(luò)

2015-05-04 14:12:43

2017-07-18 06:08:41

2023-11-27 08:21:49

Camera2API,

2017-02-14 15:37:32

KappaLambda

2025-02-18 00:10:00

2015-10-10 10:01:39

VMware數(shù)據(jù)中心

2023-12-05 10:25:24

Python類型注解

2024-11-21 15:48:40

2020-10-28 15:17:08

Go服務(wù)超時(shí)net

2009-08-04 15:55:56

OracleEPMBI

2009-10-15 09:32:39

什么是IronPythPython.NET

2017-08-09 15:27:33

python爬蟲(chóng)開(kāi)發(fā)工具

2013-12-20 17:38:37

華為統(tǒng)一通信鐵路

2021-06-14 07:39:13

比特幣區(qū)塊鏈加密貨幣
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)