zoukankan      html  css  js  c++  java
  • httplib、urllib、urllib2的区别

    参考博客:https://www.cnblogs.com/TankXiao/p/3081312.html

    http://blog.csdn.net/youfuchen/article/details/19492821

    以下是学习笔记:


     Get方法, 并且自定义header

    # -* - coding: UTF-8 -* -  
    import urllib2
    
    request = urllib2.Request("http://www.baidu.com/")
    request.add_header('content-TYPE', 'application/x-www-form-urlencoded')
    response = urllib2.urlopen(request)
    print response.getcode()
    print response.geturl()
    print response.read()

    post方法

    # -* - coding: UTF-8 -* -  
    import urllib2
    import urllib
    
    request = urllib2.Request("http://passport.cnblogs.com/login.aspx")
    request.add_header('content-TYPE', 'application/x-www-form-urlencoded')
    data={"tbUserName":"test_username", "tbPassword":"test_password"}
    
    response = urllib2.urlopen(request, urllib.urlencode(data))
    print response.getcode()
    print response.geturl()
    print response.read()

    HTTPError

    默认情况下,只要不是2XX的返回码,都会被当成错误对待。可以通过HTTPError来捕捉错误信息

    import urllib2  
      
    url = "http://www.jnrain.com/go"  
    try:  
        response = urllib2.urlopen(url)  
        print response.info()  
        print response.read()  
    except urllib2.HTTPError, e:  
        print e.getcode()  
        print e.reason  
        print e.geturl()  
        print "--"  *100
        print e.info()  
        print e.read()  

    通过捕捉错误可以打印出详细的错误信息:

    404  
    Not Found  
    http://www.jnrain.com/go  
    -------------------------  
    Server: nginx/1.4.1  
    Date: Wed, 19 Feb 2014 08:51:50 GMT  
    Content-Type: text/html; charset=gb18030  
    Content-Length: 168  
    Connection: close  
      
    <html>  
    <head><title>404 Not Found</title></head>  
    <body bgcolor="white">  
    <center><h1>404 Not Found</h1></center>  
    <hr><center>nginx/1.4.1</center>  
    </body>  
    </html> 
  • 相关阅读:
    Python开发测试工具案例分享①——开发环境搭建
    AWS—Xshell工具远程登录EC2虚拟机
    Jmeter接口测试⑧——websocker协议
    Jmeter接口测试⑦——参数化
    【转】git 2.27.0安装教程(Windows)
    Jmeter接口测试⑥——DELETE请求
    Jmeter接口测试⑤——PUT请求
    Jmeter接口测试④——响应断言
    Jmeter接口测试③——GET请求
    Jmeter接口测试②——正则提取器
  • 原文地址:https://www.cnblogs.com/mogujiang/p/5611829.html
Copyright © 2011-2022 走看看