python web編程-web客戶端編程

web應用也遵循客戶服務器架構html

瀏覽器就是一個基本的web客戶端,她實現兩個基本功能,一個是從web服務器下載文件,另外一個是渲染文件python

同瀏覽器具備相似功能以實現簡單的web客戶端的模塊式urllib以及urllib2(能夠打開須要登陸的網頁)等模塊linux

另外還有一些負載的web客戶端,它不只下載web文件,還執行其它複雜的任務,一個典型的例子就是爬蟲web

python實現爬蟲也有一些框架模塊:如Scrapy瀏覽器

使用python建立一個簡單web客戶端
你要弄清楚瀏覽器只是web客戶端的一種,並且功能有限,任何經過web的請求的應用程序都是web客戶端
好比curl以及python的urllib
爲何是urllib呢而不是httplib呢?往下閱讀
什麼是URL???構成很重要
URL用來在Web 上定位一個文檔,或者調用一個CGI 程序來爲你的客戶端產生一個文檔。
CGI產生文檔就是像一些web框架吧,特別是python的
web客戶端其實也算是 文件傳輸,最爲直接方式就是直接使用url來定位和得到文件了,其實大部分客戶端都是靠這個
因此應該首先 瞭解一下url的構成
 
python的URL模塊介紹:urllib及urlparse
Python 支持兩種不一樣的模塊,分別以不一樣的功能和兼容性來處理URL。一種是urlparse,一種
是urllib。
其中urlparse就是用來進行url解析與合成的。利用它你也能夠學習url的構成哦,關於它的用法你能夠help一下
urllib是一個高層次的模塊,urllib 模塊提供了全部你須要的功能,除非你計劃寫一個更加低層的網絡客戶端。urllib 提供
了了一個高級的Web 交流庫,支持Web 協議,HTTP, FTP 和Gopher 協議,同時也支持對本地文件的
訪問。urllib 模塊的特殊功能是利用上述協議下載數據(從因特網、局域網、主機上下載)。使用這
個模塊能夠避免使用httplib, ftplib 和gopherlib 這些模塊,除非你想用更低層的功能
urllib的主要功能就是從url來下載文件,想要了解這個模塊的功能能夠從下面幾個函數入手
urlopen()
urllib.urlretrieve()
urllib.quote() and urllib.quote_plus()
urllib.unquote() 和 urllib.unquote_plus()
urllib.urlencode()
 
urllib2
若是你打算訪問更加複雜的URL 或者想要處理更復雜的狀況如基於數字的權限驗證,重定位,
coockie 等問題,咱們建議你使用urllib2 模塊
這對於登錄來抓取數據是特別有用的
urllib3 
urllib2的升級版

Requests緩存

該模塊創建在urllib3上面的,提供了比較友好的藉口,儘可能使用它,以減小代碼量服務器

參考:http://blog.csdn.net/iloveyin/article/details/21444613網絡

wget和python綁定架構

wget是一個linux命令行工具,專一下載功能,有關下載任務合適使用它的python綁定app

curl和pycurl

curl是一個基礎的,先進的命令行工具(提供的功能相似於Request),也提供了各類語言的綁定

參考:http://www.ruanyifeng.com/blog/2011/09/curl.html
http://man.linuxde.net/curl
 
高級web客戶端
 
瀏覽器實現的實際上是一個簡單的web客戶端,基本的web客戶端從服務器下載文件,urllib以及urllib2以及上面介紹的這些模塊就是實現相似的功能
那麼高級的web客戶端就不僅是下載那麼簡單
高級Web 客戶端的一個例子就是網絡爬蟲(aka 蜘蛛和機器人)。這些程序能夠基於不一樣目的在
因特網上探索和下載頁面,其中包括:
  1. 爲 Google 和Yahoo 這類大型的搜索引擎建索引
  2. 脫機瀏覽—將文檔下載到本地,從新設定超連接,爲本地瀏覽器建立鏡像。(這個需求就是一般所說的下載整個在線的幫助文檔)
  3.  下載並保存歷史記錄或框架
  4.  Web 頁的緩存,節省再次訪問Web 站點的下載時間。
這裏給出一個爬蟲的實現
  1 #!/usr/bin/env python
  2 
  3 from sys import argv
  4 from os import makedirs, unlink, sep
  5 from os.path import isdir, exists, dirname, splitext
  6 from string import replace, find, lower
  7 from htmllib import HTMLParser
  8 from urllib import urlretrieve
  9 from urlparse import urlparse, urljoin
 10 from formatter import DumbWriter, AbstractFormatter
 11 from cStringIO import StringIO
 12 
 13 class Retriever(object):    # download Web pages
 14 
 15     def __init__(self, url):
 16         self.url = url
 17         self.file = self.filename(url)
 18 
 19     def filename(self, url, deffile='index.htm'):
 20         parsedurl = urlparse(url, 'http:', 0)  # parse path
 21         path = parsedurl[1] + parsedurl[2]
 22         ext = splitext(path)
 23         if ext[1] == '':
 24             if path[-1] == '/':
 25                 path += deffile
 26             else:
 27                 path += '/' + deffile
 28         ldir = dirname(path)    # local directory
 29     if sep != '/':        # os-indep. path separator
 30         ldir = replace(ldir, ',', sep)
 31         if not isdir(ldir):      # create archive dir if nec.
 32             if exists(ldir): unlink(ldir)
 33             makedirs(ldir)
 34         return path
 35 
 36     def download(self):        # download Web page
 37         try:
 38             retval = urllib.urlretrieve(self.url, self.file)
 39         except IOError:
 40             retval = ('*** ERROR: invalid URL "%s"' % \
 41                 self.url, )
 42         return retval
 43 
 44     def parseAndGetLinks(self):    # pars HTML, save links
 45         self.parser = HTMLParser(AbstractFormatter( \
 46             DumbWriter(StringIO())))
 47         self.parser.feed(open(self.file).read())
 48         self.parser.close()
 49         return self.parse.anchorlist
 50 
 51 class Crawler(object):        # manage entire crawling process
 52 
 53     count = 0            # static downloaded page counter
 54 
 55     def __init__(self, url):
 56         self.q = [url]
 57         self.seen = []
 58         self.dom = urlparse(url)[1]
 59 
 60     def getPage(self, url):
 61         r = Retriever(url)
 62         retval = r.download()
 63         if retval[0] == '*':     # error situation, do not parse
 64             print retval, '... skipping parse'
 65             return
 66         Crawler.count = Crawler.count + 1
 67         print '\n(', Crawler.count, ')'
 68         print 'URL:', url
 69         print 'FILE:', retval[0]
 70         self.seen.append(url)
 71 
 72         links = r.parseAndGetLinks()  # get and process links
 73         for eachLink in links:
 74             if eachLink[:4] != 'http' and \
 75                     find(eachLink, '://') == -1:
 76                 eachLink = urljoin(url, eachLink)
 77             print '* ', eachLink,
 78 
 79             if find(lower(eachLink), 'mailto:') != -1:
 80                 print '... discarded, mailto link'
 81                 continue
 82 
 83             if eachLink not in self.seen:
 84                 if find(eachLink, self.dom) == -1:
 85                     print '... discarded, not in domain'
 86                 else:
 87                     if eachLink not in self.q:
 88                         self.q.append(eachLink)
 89                         print '... new, added to Q'
 90                     else:
 91                         print '... discarded, already in Q'
 92             else:
 93                     print '... discarded, already processed'
 94 
 95     def go(self):                # process links in queue
 96         while self.q:
 97             url = self.q.pop()
 98             self.getPage(url)
 99 
100 def main():
101     if len(argv) > 1:
102         url = argv[1]
103     else:
104         try:
105             url = raw_input('Enter starting URL: ')
106         except (KeyboardInterrupt, EOFError):
107             url = ''
108 
109     if not url: return
110     robot = Crawler(url)
111     robot.go()
112 
113 if __name__ == '__main__':
114     main()
View Code

 

實際上這裏也有一些爬蟲的庫,很少介紹
相關文章
相關標籤/搜索