『壹』 python的httplib,urllib和urllib2的區別及用
他們的區別
urllib和urllib2
urllib 和urllib2都是接受URL請求的相關模塊,但是urllib2可以接受一個Request類的實例來設置URL請求的headers,urllib僅可以接受URL。
這意味著,你不可以偽裝你的User Agent字元串等。
urllib提供urlencode方法用來GET查詢字元串的產生,而urllib2沒有。這是為何urllib常和urllib2一起使用的原因。
目前的大部分http請求都是通過urllib2來訪問的
httplib
httplib實現了HTTP和HTTPS的客戶端協議,一般不直接使用,在python更高層的封裝模塊中(urllib,urllib2)使用了它的http實現。
urllib簡單用法
urllib.urlopen(url[, data[, proxies]]) :
詳細使用方法見
urllib學習
urllib2簡單用法
最簡單的形式
import urllib2
response=urllib2.urlopen('http://www.douban.com')
html=response.read()
實際步驟:
1、urllib2.Request()的功能是構造一個請求信息,返回的req就是一個構造好的請求
2、urllib2.urlopen()的功能是發送剛剛構造好的請求req,並返回一個文件類的對象response,包括了所有的返回信息。
3、通過response.read()可以讀取到response裡面的html,通過response.info()可以讀到一些額外的信息。
如下:
#!/usr/bin/env python
import urllib2
req = urllib2.Request("http://www.douban.com")
response = urllib2.urlopen(req)
html = response.read()
print html
有時你會碰到,程序也對,但是伺服器拒絕你的訪問。這是為什麼呢?問題出在請求中的頭信息(header)。 有的服務端有潔癖,不喜歡程序來觸摸它。這個時候你需要將你的程序偽裝成瀏覽器來發出請求。請求的方式就包含在header中。
常見的情形:
import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'# 將user_agent寫入頭信息
values = {'name' : 'who','password':'123456'}
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
values是post數據
GET方法
例如網路:
網路是通過http://www..com/s?wd=XXX 來進行查詢的,這樣我們需要將{『wd』:』xxx』}這個字典進行urlencode
#coding:utf-8
import urllib
import urllib2
url = 'http://www..com/s'
values = {'wd':'D_in'}
data = urllib.urlencode(values)
print data
url2 = url+'?'+data
response = urllib2.urlopen(url2)
the_page = response.read()
print the_page
POST方法
import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' //將user_agent寫入頭信息
values = {'name' : 'who','password':'123456'} //post數據
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values) //對post數據進行url編碼
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
urllib2帶cookie的使用
#coding:utf-8
import urllib2,urllib
import cookielib
url = r'http://www.renren.com/ajaxLogin'
#創建一個cj的cookie的容器
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#將要POST出去的數據進行編碼
data = urllib.urlencode({"email":email,"password":pass})
r = opener.open(url,data)
print cj
httplib簡單用法
簡單示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import httplib
import urllib
def sendhttp():
data = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection('bugs.python.org')
conn.request('POST', '/', data, headers)
httpres = conn.getresponse()
print httpres.status
print httpres.reason
print httpres.read()
if __name__ == '__main__':
sendhttp()
具體用法見
httplib模塊
python 3.x中urllib庫和urilib2庫合並成了urllib庫。其中、
首先你導入模塊由
import urllib
import urllib2
變成了
import urllib.request
然後是urllib2中的方法使用變成了如下
urllib2.urlopen()變成了urllib.request.urlopen()
urllib2.Request()變成了urllib.request.Request()
urllib2.URLError 變成了urllib.error.URLError
而當你想使用urllib 帶數據的post請求時,
在python2中
urllib.urlencode(data)
而在python3中就變成了
urllib.parse.urlencode(data)
腳本使用舉例:
python 2中
import urllib
import urllib2
import json
from config import settings
def url_request(self, action, url, **extra_data): abs_url = "http://%s:%s/%s" % (settings.configs['Server'],
settings.configs["ServerPort"],
url)
if action in ('get', 'GET'):
print(abs_url, extra_data)
try:
req = urllib2.Request(abs_url)
req_data = urllib2.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
# print "-->server response:",callback
return callback
except urllib2.URLError as e:
exit("\033[31;1m%s\033[0m" % e)
elif action in ('post', 'POST'):
# print(abs_url,extra_data['params'])
try:
data_encode = urllib.urlencode(extra_data['params'])
req = urllib2.Request(url=abs_url, data=data_encode)
res_data = urllib2.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = res_data.read()
callback = json.loads(callback)
print("\033[31;1m[%s]:[%s]\033[0m response:\n%s" % (action, abs_url, callback))
return callback
except Exception as e:
print('---exec', e)
exit("\033[31;1m%s\033[0m" % e)
python3.x中
import urllib.request
import json
from config import settings
def url_request(self, action, url, **extra_data):
abs_url = 'http://%s:%s/%s/' % (settings.configs['ServerIp'], settings.configs['ServerPort'], url)
if action in ('get', 'Get'): # get請求
print(action, extra_data)try:
req = urllib.request.Request(abs_url)
req_data = urllib.request.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
return callback
except urllib.error.URLError as e:
exit("\033[31;1m%s\033[0m" % e)
elif action in ('post', 'POST'): # post數據到伺服器端
try:
data_encode = urllib.parse.urlencode(extra_data['params'])
req = urllib.request.Request(url=abs_url, data=data_encode)
req_data = urllib.request.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
callback = json.loads(callback.decode())
return callback
except urllib.request.URLError as e:
print('---exec', e)
exit("\033[31;1m%s\033[0m" % e)
settings配置如下:
configs = {
'HostID': 2,
"Server": "localhost",
"ServerPort": 8000,
"urls": {
'get_configs': ['api/client/config', 'get'], #acquire all the services will be monitored
'service_report': ['api/client/service/report/', 'post'],
},
'RequestTimeout': 30,
'ConfigUpdateInterval': 300, # 5 mins as default
}
『貳』 python 怎麼導入httplib
例子
#!/usr/bin/envpython
#-*-coding:utf-8-*-
importhttplib
importurllib
defsendhttp():
data=urllib.urlencode({'@number':12524,'@type':'issue','@action':'show'})
headers={"Content-type":"application/x-www-form-urlencoded",
"Accept":"text/plain"}
conn=httplib.HTTPConnection('bugs.python.org')
conn.request('POST','/',data,headers)
httpres=conn.getresponse()
printhttpres.status
printhttpres.reason
printhttpres.read()
if__name__=='__main__':
sendhttp()
『叄』 python httplib2 urllib區別
功能上沒什麼區別吧,httlib2比urllib更進一步把,比如在長鏈接支持方面,運行速度方面更優越一點兒,適用情況差不多。
個人感覺pycurl更強大一點。
『肆』 python3沒有httplib了嗎
1、有,python3把httplib改了名字,對應的庫是http.client
2、網址是:
https://docs.python.org/3.4/library/http.client.html
https://docs.python.org/2/library/httplib.html
『伍』 python http 連接問題,urllib2和httplib2
都沒把問題描述清楚,相幫也幫不了。
『陸』 請教個python httplib2傳遞參數問題
樓主的理解沒有問題啊
.
python中函數的實參傳遞規則是:
標注了參數名的就要按參數名傳遞,打亂順序的情況下一定要加參數名,否則會混亂的。
沒有預設的實參情況下就會依次傳遞,如果不夠的話,後面的會自動去取自己的預設值。
如果實參的數量比
『柒』 求助python3 302重定向 鎐ookie問題
通過昨天寫的python腳本,我已經注冊激活了50個box.net賬號,用作上傳文件。
今天我繼續寫代碼,用來自動登錄box.net並獲取所有文件的分享鏈接。
不過測試的時候出現了點問題,賬號信息正確,但總是登錄不成功。
headers中referer、user-agent都有偽造,cookie也有發送。
通過設置debuglevel=1跟蹤http請求,最終發現了問題:
1
2
3
httpHandler = urllib2.HTTPHandler(debuglevel=1)
httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
self.opener = urllib2.build_opener(httpHandler, httpsHandler)
urllib2很聰明,在發現HttpResponse中有重定向(301, 302)時會自動轉向請求這個新的URL,
但urllib2有個嚴重的問題,它沒有帶著cookie去請求新的URL。
這也是說,前期我們通過一個POST請求來獲取cookie(對應著伺服器上的session),
但urllib2卻沒有帶著必要的cookie去訪問需要授權的頁面。
一開始我是想直接用httplib的,考慮到前後一致性才全部用urllib2,結果urllib2又出問題。。。
解決這個問題,可以:
1. 換httplib來實現,它不會像urllib2會自動處理重定向,cookie不會丟
2. 截獲重定向,禁止urllib2自動處理
我選擇了重寫urllib2.HTTPRedirectHandler的http_error_302方法,截獲302,讓urllib2不再處理302:
1
2
3
class HttpRedirect_Handler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
pass
然後在urllib2.build_opener方法中用HttpRedirect_Handler的一個實例做參數,例如:
1
2
self.opener = urllib2.build_opener(HttpRedirect_Handler(),
urllib2.HTTPCookieProcessor(self.cookie))
這樣,當我們用上述opener去POST登錄時,遇到302就不會再自動轉向了,
登錄成功獲取到的cookie也不會丟。
後面再帶著self.cookie去請求需要授權的頁面,就可以獲取到正確的內容了。