Python網路頁面抓取和頁面分析__Python

來源:互聯網
上載者:User
(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();    



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.