Python自动化测试 (九)urllib2 发送HTTP Request
生活随笔
收集整理的這篇文章主要介紹了
Python自动化测试 (九)urllib2 发送HTTP Request
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
urllib2 是Python自帶的標準模塊, 用來發送HTTP Request的。? 類似于 .NET中的,? HttpWebRequest類
?
urllib2 的優點
Python urllib2 發出的HTTP Request, 能自動被Fiddler截獲, 方便了調試。
Python 可以自動處理Cookie
?
urllib2 的缺點
Python urllib2 發出的http Request, 中的header 會被修改成“首字母大寫”,
比如你的代碼里寫的header 是: content-TYPE=application/x-www-form-urlencoded ,? 會被修改為 Content-Type=application/x-www-form-urlencoded
?
實例一,? Get方法, 并且自定義header
?
# -* - coding: UTF-8 -* - import urllib2request = 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 urllibrequest = 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 cookielibcj = 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之一?
?
?
?
總結
以上是生活随笔為你收集整理的Python自动化测试 (九)urllib2 发送HTTP Request的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: django之创建第6-1个项目-自定义
- 下一篇: websocket python爬虫_p