urllib2 是Python自帶的標準模塊, 用來發送HTTP Request的。 相似於 .NET中的, HttpWebRequest類web
Python urllib2 發出的HTTP Request, 能自動被Fiddler截獲, 方便了調試。cookie
Python 能夠自動處理Cookieapp
Python urllib2 發出的http Request, 中的header 會被修改爲「首字母大寫」,post
好比你的代碼裏寫的header 是: content-TYPE=application/x-www-form-urlencoded , 會被修改成 Content-Type=application/x-www-form-urlencodedui
# -* - 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()
# -* - 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()
# -* - 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