python urllib2模塊學習
urllib2是urllib擴展的庫,不僅可以使用http協(xié)議,而且可以擴展到ftp等協(xié)議。
常用函數(shù)一:urlopen(url, data=None, timeout=
最基本的用法和urllib下面的urlopen(url, data=None)一樣,傳遞一個URL參數(shù), 添加post需要的data,返回值是一個類似于file的對象, 可以使用通常的文件操作來操作這個對象,比如read,write等。
urllib2.urlopen()參數(shù)可以用一個request的對象來代替URL,而且增加了一個URLError異常,對于HTTP協(xié)議的錯誤,增加了一個HTTPError的異常,其中這個HTTPError自動變成一個合法的response來返回。
最簡單的使用情況:
import urllib2
url = "http://www.baidu.com"
response = urllib2.urlopen(url)
print response.info()
注意url一定要添加協(xié)議類型,也就是http://,其中response.info()可以獲取返回來的http response head的信息,response.read()用來獲取response的body信息。
默認如果只有一個url參數(shù),那么默認是使用HTTP GET 的方法來訪問url。
如果訪問的url不存在, 那么會返回一個HTTPError
import urllib2
url = "http://www.jnrain.com/go"
response = urllib2.urlopen(url)
print response.info()
print response.read()
其中錯誤信息如下:
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
可以看到是404錯誤,默認情況下,只要不是2XX的返回碼,都會被當成錯誤對待??梢酝ㄟ^HTTPError來捕捉錯誤信息
import urllib2
url = "http://www.jnrain.com/go"
try:
response = urllib2.urlopen(url)
print response.info()
print response.read()
except urllib2.HTTPError, e:
print e.getcode()
print e.reason
print e.geturl()
print "-------------------------"
print e.info()
print e.read()
通過捕捉錯誤可以打印出詳細的錯誤信息:
404
Not Found
http://www.jnrain.com/go
-------------------------
Server: nginx/1.4.1
Date: Wed, 19 Feb 2014 08:51:50 GMT
Content-Type: text/html; charset=gb18030
Content-Length: 168
Connection: close
404 Not Found
404 Not Found
nginx/1.4.1
import urllib2
request = urllib2.Request("http://www.jnrain.com/wForum/logon.php")
request.add_header('User-agent', 'Internet Explorer')
try:
response = urllib2.urlopen(request)
except urllib2.URLError, e:
print e.code
headers = response.info()
data = response.read()
這樣我們的http request頭部中的user-agent就變成了Internet Explorer,如果創(chuàng)建reques的時候不添加data, 那么默認使用GET方法,如果添加data,那么使用POST方法,下面是Request類中的方法:
def get_method(self):
if self.has_data():
return "POST"
else:
return "GET"
# XXX these helper methods are lame
def add_data(self, data):
self.data = data
def has_data(self):
return self.data is not None
def get_data(self):
return self.data
可以在執(zhí)行時輸出debug信息
import urllib2
httpHandler = urllib2.HTTPHandler(debuglevel=1)
httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
opener = urllib2.build_opener(httpHandler, httpsHandler)
urllib2.install_opener(opener)
url = "http://www.baidu.com"
request = urllib2.Request(url)
request.add_header("User-Agent", "Firefox")
response = urllib2.urlopen(request)
只要定義debuglevel設置為1就可以了
post 表單的相關使用:
import urllib2
import urllib
httpHandler = urllib2.HTTPHandler(debuglevel=1)
httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
opener = urllib2.build_opener(httpHandler, httpsHandler)
urllib2.install_opener(opener)
url = "https://www.account.xiaomi.com/pass/serviceLoginAuth2"
postdata = urllib.urlencode({"user":"XXXXXXX",
"_json":"true",
"pwd":"XXXXXXX",
"sid":"eshop",
"_sign":"g7K1HSZPYIaO4tSlhS1xdDJBPV8=",
"callback":"http://order.xiaomi.com/login/callback?followup=http%3A%2F%2Fwww.xiaomi.com%2Findex.php&sign=ZjEwMWVlOTY3MWM1OGE3YjYxNGRiZjQ5MzJmYjI5NDE0ZWY0NzY5Mw,," })
request = urllib2.Request(url, data=postdata)
request.add_header("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0")
try:
response = urllib2.urlopen(request)
print response.info()
print response.read()
except urllib2.HTTPError,e:
print e.getcode()
print e.reason
上面是小米的自動登陸界面的表單post提交,可以使用firefox和Tamper Data來獲取post需要的參數(shù),然后填寫正確的用戶名和密碼就可以了。