日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python自动化测试 (九)urllib2 发送HTTP Request

發布時間:2024/4/17 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。