欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python网络学习(05)

程序员文章站 2022-04-08 21:41:17
...
# coding:utf-8
'''
Httplib微型浏览器
'''
import httplib

Remote_host = 'www.python.org'
Remote_Path = '/'
USE_Aget ='''Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'''


class HttpClent(object):
    def __init__(self, host):
        self.host = host

    def fetch(self, port):
        self.port = port
        http = httplib.HTTP(self.port)
        # preprader Header
        http.putrequest('GET', '/')
        http.putheader('User-Agent', USE_Aget)
        http.putheader('HOST', self.host)
        http.putheader('Accept', '*/*')
        http.endheaders()

        try:
             errcode, errmsg, header = http.getreply(True)
        except Exception, e:
           print '连接失败'
        else:
           print 'Got page from %s' % self.host
        file = http.getfile()
        return file.read()


if __name__ == "__main__":
    demo = HttpClent(Remote_host)
    print demo.fetch(Remote_Path)

  从HTPP站点下载文件