您的位置:首页 > 编程语言 > Python开发

python web编程-web客户端编程

2014-11-05 20:14 120 查看

web应用也遵循客户服务器架构

浏览器就是一个基本的web客户端,她实现两个基本功能,一个是从web服务器下载文件,另一个是渲染文件

同浏览器具有类似功能以实现简单的web客户端的模块式urllib以及urllib2(可以打开需要登录的网页)等模块

另外还有一些负载的web客户端,它不仅下载web文件,还执行其它复杂的任务,一个典型的例子就是爬虫

python实现爬虫也有一些框架模块:如Scrapy



使用python创建一个简单web客户端
你要弄清楚浏览器只是web客户端的一种,而且功能有限,任何通过web的请求的应用程序都是web客户端
比如curl以及python的urllib
为什么是urllib呢而不是httplib呢?往下阅读
什么是URL???构成很重要
URL用来在Web 上定位一个文档,或者调用一个CGI 程序来为你的客户端产生一个文档。
CGI产生文档就是像一些web框架吧,特别是python的
web客户端其实也算是文件传输,最为直接方式就是直接使用url来定位和获得文件了,其实大部分客户端都是靠这个
所以应该首先了解一下url的构成
http://zh.wikipedia.org/zh/%E7%BB%9F%E4%B8%80%E8%B5%84%E6%BA%90%E5%AE%9A%E4%BD%8D%E7%AC%A6

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 模块
这对于登陆来抓取数据是特别有用的

高级web客户端

浏览器实现的其实是一个简单的web客户端,基本的web客户端从服务器下载文件,urllib以及urllib2以及上面介绍的这些模块就是实现类似的功能
那么高级的web客户端就不只是下载那么简单
高级Web 客户端的一个例子就是网络爬虫(aka 蜘蛛和机器人)。这些程序可以基于不同目的在
因特网上探索和下载页面,其中包括:

为 Google 和Yahoo 这类大型的搜索引擎建索引

脱机浏览—将文档下载到本地,重新设定超链接,为本地浏览器创建镜像。(这个需求就是通常所说的下载整个在线的帮助文档)

下载并保存历史记录或框架

Web 页的缓存,节省再次访问Web 站点的下载时间。

这里给出一个爬虫的实现

#!/usr/bin/env python

from sys import argv
from os import makedirs, unlink, sep
from os.path import isdir, exists, dirname, splitext
from string import replace, find, lower
from htmllib import HTMLParser
from urllib import urlretrieve
from urlparse import urlparse, urljoin
from formatter import DumbWriter, AbstractFormatter
from cStringIO import StringIO

class Retriever(object):    # download Web pages

def __init__(self, url):
self.url = url
self.file = self.filename(url)

def filename(self, url, deffile='index.htm'):
parsedurl = urlparse(url, 'http:', 0)  # parse path
path = parsedurl[1] + parsedurl[2]
ext = splitext(path)
if ext[1] == '':
if path[-1] == '/':
path += deffile
else:
path += '/' + deffile
ldir = dirname(path)    # local directory
if sep != '/':        # os-indep. path separator
ldir = replace(ldir, ',', sep)
if not isdir(ldir):      # create archive dir if nec.
if exists(ldir): unlink(ldir)
makedirs(ldir)
return path

def download(self):        # download Web page
try:
retval = urllib.urlretrieve(self.url, self.file)
except IOError:
retval = ('*** ERROR: invalid URL "%s"' % \
self.url, )
return retval

def parseAndGetLinks(self):    # pars HTML, save links
self.parser = HTMLParser(AbstractFormatter( \
DumbWriter(StringIO())))
self.parser.feed(open(self.file).read())
self.parser.close()
return self.parse.anchorlist

class Crawler(object):        # manage entire crawling process

count = 0            # static downloaded page counter

def __init__(self, url):
self.q = [url]
self.seen = []
self.dom = urlparse(url)[1]

def getPage(self, url):
r = Retriever(url)
retval = r.download()
if retval[0] == '*':     # error situation, do not parse
print retval, '... skipping parse'
return
Crawler.count = Crawler.count + 1
print '\n(', Crawler.count, ')'
print 'URL:', url
print 'FILE:', retval[0]
self.seen.append(url)

links = r.parseAndGetLinks()  # get and process links
for eachLink in links:
if eachLink[:4] != 'http' and \
find(eachLink, '://') == -1:
eachLink = urljoin(url, eachLink)
print '* ', eachLink,

if find(lower(eachLink), 'mailto:') != -1:
print '... discarded, mailto link'
continue

if eachLink not in self.seen:
if find(eachLink, self.dom) == -1:
print '... discarded, not in domain'
else:
if eachLink not in self.q:
self.q.append(eachLink)
print '... new, added to Q'
else:
print '... discarded, already in Q'
else:
print '... discarded, already processed'

def go(self):                # process links in queue
while self.q:
url = self.q.pop()
self.getPage(url)

def main():
if len(argv) > 1:
url = argv[1]
else:
try:
url = raw_input('Enter starting URL: ')
except (KeyboardInterrupt, EOFError):
url = ''

if not url: return
robot = Crawler(url)
robot.go()

if __name__ == '__main__':
main()


View Code

实际上这里也有一些爬虫的库,不多介绍
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: