07:urllib與urllib2基本使用

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

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

  一、encode和unquote僅對一個字符串進行轉換json

import urllib
s = '張三'
s_encode = urllib.quote(s)
print s_encode  
# 執行結果:%E5%BC%A0%E4%B8%89
encode
#二、url unquote
import urllib
s = '%E5%BC%A0%E4%B8%89'
s_decode = urllib.unquote(s)
print s_decode 
# 執行結果:張三
unquote

  二、urlencode api

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

# 二、unquote解析url
data = 'name=%E5%BC%A0%E4%B8%89&sex=%E7%94%B7'
print urllib.unquote(data)
# 執行結果:name=張三&sex=男
urlencode
相關文章
相關標籤/搜索