• python网络编程 — HTTP客户端


    A simple http client.

    It gets the contents of special webserver page and print it.(Default path is "/")

    #!/usr/share/env python
    #coding:utf-8
    
    import argparse
    import httplib
    
    #设置默认访问url和端口
    REMOTE_SERVER_HOST='www.python.org'
    REMOTE_SERVER_PATH='/'
    
    
    class HTTPClient(object):
        """
            docstring for HTTPClient
            Eg: python HTTPClient.py --host=www.iana.org 
            python HTTPClient.py --host=www.iana.org --path='/domains/reserved'
        """
        def __init__(self, host):
            self.host = host
    
        def fetch(self,path):
            http = httplib.HTTP(self.host)
    
            #设置请求头信息
            http.putrequest("GET",path)
            http.putheader("User-Agent",__file__)
            http.putheader("Host",self.host)
            http.putheader("Accept","*/*")
            http.endheaders()
    
            try:
                #getreply方法返回service code ,service reseason,RFC82 headers
                errcode,errmsg,headers = http.getreply()
            except Exception,e:
                print "Client failed code: %s message: %s headers: %s" %(errcode,errmsg,headers)
            else:
                print "Got homepage from %s" %self.host
    
                #打印获取的内容
                file = http.getfile()
                return file.read()
    
    if __name__ == '__main__':
        parse = argparse.ArgumentParser(description='HTTP Client Example')
        parse.add_argument('--host',action="store",dest="host",default=REMOTE_SERVER_HOST)
        parse.add_argument('--path',action="store",dest="path",default=REMOTE_SERVER_PATH)
        given_args = parse.parse_args()
        host,path = given_args.host,given_args.path
        client = HTTPClient(host)
        print client.fetch(path)
    

      

  • 相关阅读:
    css--盒子模型
    目标爬取社会信用码
    KFC-位置分页爬虫
    百度翻译-爬虫
    网页采集器-UA伪装
    python模块2
    python模块
    go入门
    python垃圾回收机制
    Python高级用法
  • 原文地址:https://www.cnblogs.com/ssooking/p/5879793.html
Copyright © 2020-2023  润新知