(1)安裝第三方庫httplib2
首先下載python的httplib2的安裝包,下載地址為: http://code.google.com/p/httplib2/downloads/list;其次, 在dos視窗下進入httplib2的解壓目錄,執行命令:python setup.py install 。 即完成安裝。然後在PyDev中加入這個第三方庫,windows->preferences->PyDev->Editor->Interpreter-Python->Libraries->New Folder
http://docs.python.org/library/index.html 這個網址給出各種lib庫的講解。
(2)下面的例子是抓取http://guangzhou.8684.cn/x_24f5dad9這個網址的資訊,然後通過Regex,提取其中的公交線路和公交網站資訊。
#!/usr/bin/python# -*- coding: utf-8 -*-'''Created on 2013-8-26@author: chenll''''''【工具需求】抓取廣州1路線的公交線路資料和網站資料。'''import os,httplib2,re#擷取HTMl頁面內容def getContent(): h = httplib2.Http(".cache") resp, content = h.request("http://guangzhou.8684.cn/x_24f5dad9", headers={'cache-control':'no-cache'}) return content.decode('gbk').encode('utf-8') ;def featch(): content = getContent(); #start:<div class="hc_d3" id="show1"> #end:<h2 class="hc_re"> startIndex = content.index('<div class="hc_d3" id="show1">'); endIndex = content.index('<h2 class="hc_re">'); subContent = content[startIndex:endIndex]; reg = r'[\s\S]*<h2\s*class="hc_p6">([\s\S]*)<span\s*id="ad581"></span></h2>\s*<p\s*class="hc_p7"><span>([\S]*)</span>\s*<span>([\s\S]*)</span>\s*<span>([\s\S]*)</span>\s*<a href="[\s\S]*">[\s\S]*</a>\s*</p>\s*<p\s*class="hc_p8">([\s\S]*)'; match = re.match(reg,subContent); if match: #線路名稱 lineName = match.group(1); #線路類型 lineType = match.group(2); #起始首班車時間 lineTime = match.group(3); #車票 tickect = match.group(4); #網站資訊 stationInfo = match.group(5); reg = r'\s*<i>去程:</i>([\s\S]*)<i>回程:</i>([\s\S]*)' match1 = re.match(reg,stationInfo); if match1: #去程 qc = match1.group(1) qcArray = qc.split('-'); for each in qcArray: reg = r'\s*<a\s*href="[\s\S]*">([\s\S]*)</a>\s*' match2 = re.match(reg,each); if match2: #去程網站 print match2.group(1) #回程 hc = match1.group(2); hcArray = hc.split('-'); for each in hcArray: reg = r'\s*<a\s*href="[\s\S]*">([\s\S]*)</a>\s*' match2 = re.match(reg,each); if match2: #回程網站 print match2.group(1)#定義主調函數def main(): featch();if __name__ == '__main__': main();