Python自動化測試 (九)urllib2 發送HTTP Request

urllib2 是Python自帶的標準模塊, 用來發送HTTP Request的。  相似於 .NET中的,  HttpWebRequest類web

 

urllib2 的優勢

Python urllib2 發出的HTTP Request, 能自動被Fiddler截獲, 方便了調試。cookie

Python 能夠自動處理Cookieapp

 

urllib2 的缺點

Python urllib2 發出的http Request, 中的header 會被修改爲「首字母大寫」,post

好比你的代碼裏寫的header 是: content-TYPE=application/x-www-form-urlencoded ,  會被修改成 Content-Type=application/x-www-form-urlencodedui

 

實例一,  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()

 

實例三: Cookie 的處理

 

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

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

request = urllib2.Request("https://dynamic.12306.cn/otsweb/")
request.add_header('content-TYPE', 'application/x-www-form-urlencoded')
data={"tbUserName":"test_username", "tbPassword":"test_password"}

response = opener.open(request, urllib.urlencode(data))

# send again, you will see cookie sent to web server
response = opener.open(request, urllib.urlencode(data))

print response.getcode()
print response.geturl()
print response.read()

 

實例四:如何處理跳轉

建立Opener時, ul2.HTTPRedirectHandler是默認被加上的handler之一 url

相關文章
相關標籤/搜索