urllib与urllib2基本使用

参考博客:https://blog.csdn.net/chendong_/article/details/51973499

1.1 urllib2发送get请求

# -*- coding:UTF-8 -*-
import urllib2

response = urllib2.urlopen("https://www.baidu.com/")
print response.read()
urllib2.urlopen(url) 不带参数的get请求 :法1
# -*- coding:UTF-8 -*-

import urllib2
import urllib

url = 'http://127.0.0.1:8000/login/?'
para = {'name':'zhangsan','age':100}
req = urllib2.Request(url + urllib.urlencode(para))
page = urllib2.urlopen(req)
print page.read()

# 服务器端结果:{u'name': [u'zhangsan']
urllib2.Request(url,data) 带参数的get请求:法2

1.2 urllib2发送post请求

# -*- coding:UTF-8 -*-

import urllib2
import urllib
values = {'username':'zhangsan','pwd':'123456'}
data = urllib.urlencode(values)
url = "http://127.0.0.1:8000/login/"
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
print response.read()
urllib2发送post请求
import urllib2
import json

data = {
    'a': 123,
    'b': 456
}
headers = {'Content-Type': 'application/json'}
request = urllib2.Request(url='url', headers=headers, data=json.dumps(data))
response = urllib2.urlopen(request)
post方式发送json参数

1.3 高级用法:设置Headers

# -*- coding:UTF-8 -*-

import urllib2
import urllib

url = 'http://127.0.0.1:8000/login/'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {"username":"1098918523@qq.com", "password":"341204baiduhi"}
headers = {'User_Agent': user_agent}
data = urllib.urlencode(values)
request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request)
print response.read()
urllib2设置请求头信息

1.4 urllib2发送put请求 

def send_put(url,values):
    data = {
        'a': 123,
        'b': 456
    }
    headers = {'Content-Type': 'application/json'}
    request = urllib2.Request(url=url, headers=headers, data=json.dumps(data))
    request.get_method = lambda: 'PUT'
    response = urllib2.urlopen(request)
    print response.read()

if __name__=="__main__":
    values = {'name':'新添加组01','fid':'314'}
    url = "http://127.0.0.1:8000/api/operate/dept"
    send_put(url,values)
urllib2发送put请求

1.5 python2中urllib2对url进行urlencode与unquote

  1、encode和unquote仅对一个字符串进行转换

import urllib
s = '张三'
s_encode = urllib.quote(s)
print s_encode  
# 执行结果:%E5%BC%A0%E4%B8%89
encode
#2、url unquote
import urllib
s = '%E5%BC%A0%E4%B8%89'
s_decode = urllib.unquote(s)
print s_decode 
# 执行结果:张三
unquote

  2、urlencode 

# 1、urlencode
import urllib
data={"name":"张三","sex":""}
print urllib.urlencode(data)
# 执行结果:name=%E5%BC%A0%E4%B8%89&sex=%E7%94%B7

# 2、unquote解析url
data = 'name=%E5%BC%A0%E4%B8%89&sex=%E7%94%B7'
print urllib.unquote(data)
# 执行结果:name=张三&sex=男
urlencode
原文地址:https://www.cnblogs.com/jiaxinzhu/p/12596078.html