導航:首頁 > 編程語言 > pythonhttplib教程

pythonhttplib教程

發布時間:2023-01-26 19:32:15

Ⅰ 怎麼用http上傳一個文件到伺服器 python

首先,標准HTTP協議對上傳文件等表單的定義在這里:wwwietforg/rfc/rfc1867txt 大概數據包格式如下:

單文件:

Content-type: multipart/form-data, boundary=AaB03x

--AaB03x
content-disposition: form-data; name="field1"

Joe Blow
--AaB03x
content-disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--
多文件:

Content-type: multipart/form-data, boundary=AaB03x

--AaB03x
content-disposition: form-data; name="field1"

Joe Blow
--AaB03x
content-disposition: form-data; name="pics"
Content-type: multipart/mixed, boundary=BbC04y

--BbC04y
Content-disposition: attachment; filename="file1.txt"
其次,python上傳文件的幾種方法:

1 自己封裝HTTP的POST數據包:http//stackoverflowcom/questions/680305/using-multipartposthandler-to-post-form-data-with-python

import httplibimport mimetypesdef post_multipart(host, selector, fields, files): content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTP(host) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body))) h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() return h.file.read() def encode_multipart_formdata(fields, files): LIMIT = '----------lImIt_of_THE_fIle_eW_$' CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + LIMIT) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files:

Ⅱ python 怎樣爬去網頁的內容

用python爬取網頁信息的話,需要學習幾個模塊,urllib,urllib2,urllib3,requests,httplib等等模塊,還要學習re模塊(也就是正則表達式)。根據不同的場景使用不同的模塊來高效快速的解決問題。

最開始我建議你還是從最簡單的urllib模塊學起,比如爬新浪首頁(聲明:本代碼只做學術研究,絕無攻擊用意):

這樣就把新浪首頁的源代碼爬取到了,這是整個網頁信息,如果你要提取你覺得有用的信息得學會使用字元串方法或者正則表達式了。

平時多看看網上的文章和教程,很快就能學會的。

補充一點:以上使用的環境是python2,在python3中,已經把urllib,urllib2,urllib3整合為一個包,而不再有這幾個單詞為名字的模塊

Ⅲ python怎麼做伺服器偽裝HTTP協議

HTTP協議是很簡單的一個協議,沒必要偽裝的。而且python有很多web框架。其中比較小巧的一個是web.py ,其網址是http://webpy.org/ 復雜的框架也很多,比如很流行的django之類的。下面的httplib實際上是模擬客戶端的。

Ⅳ 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使用pip安裝httplib模塊

直接使用命令安裝即可,以下為安裝命令:
切需到pip所在目錄,執行
pip install httplib

Ⅵ 如何解決python中httplib用get方式

在python中 也有兩種請求方式:get和post 先介紹下get方式:如圖 python發送POST請求:代碼如下:

Ⅶ 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的客戶端協議,一般不直接使用,在更高層的封裝模塊中(urllib,urllib2)使用了它的http實現。

urllib簡單用法
urllib.urlopen(url[, data[, proxies]]) :
[python] view plain

google = urllib.urlopen('')
print 'http header:/n', google.info()
print 'http status:', google.getcode()
print 'url:', google.geturl()
for line in google: # 就像在操作本地文件
print line,
google.close()

詳細使用方法見
urllib學習

urllib2簡單用法
最簡單的形式
import urllib2
response=urllib2.urlopen(')
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("")
response = urllib2.urlopen(req)
html = response.read()
print html

有時你會碰到,程序也對,但是伺服器拒絕你的訪問。這是為什麼呢?問題出在請求中的頭信息(header)。 有的服務端有潔癖,不喜歡程序來觸摸它。這個時候你需要將你的程序偽裝成瀏覽器來發出請求。請求的方式就包含在header中。
常見的情形:

import urllib
import urllib2
url = '
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方法
例如網路:
,這樣我們需要將{『wd』:』xxx』}這個字典進行urlencode

#coding:utf-8
import urllib
import urllib2
url = ''
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 = ''
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''

#創建一個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 http請求時使用GET返回成功,使用POST卻返回失敗

看來你是對於網頁抓取的邏輯不太熟悉,所以自己先去看看:
【整理】關於抓取網頁,分析網頁內容,模擬登陸網站的邏輯/流程和注意事項

看懂了邏輯後,再去學慣用工具如何抓取出來相關的邏輯:
【教程】手把手教你如何利用工具(IE9的F12)去分析模擬登陸網站(網路首頁)的內部邏輯過程

最後,再學習如何用python語言實現這些邏輯:
【教程】抓取網並提取網頁中所需要的信息 之 Python版
【教程】模擬登陸網站 之 Python版(內含兩種版本的完整的可運行的代碼)

(這里不給貼地址,自己或google搜標題即可找到我的這些帖子)

Ⅸ 如何用Python寫一個http post請求

python發送post和get請求
get請求:
使用get方式時,請求數據直接放在url中。
方法一、
importurllib
importurllib2
url="<ahref="http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa""target="_blank">http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"</a>
req=urllib2.Request(url)
printreq
res_data=urllib2.urlopen(req)
res=res_data.read()
printres
方法二、
importhttplib
url="<ahref="http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa""target="_blank">http://192.168.81.16/cgi-bin/python_test/test.py?ServiceCode=aaaa"</a>
conn=httplib.HTTPConnection("192.168.81.16")
conn.request(method="GET",url=url)
response=conn.getresponse()
res=response.read()
printres
post請求:
使用post方式時,數據放在data或者body中,不能放在url中,放在url中將被忽略。
方法一、
importurllib
importurllib2
test_data={'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode=urllib.urlencode(test_data)
requrl="<ahref="http://192.168.81.16/cgi-bin/python_test/test.py""target="_blank">http://192.168.81.16/cgi-bin/python_test/test.py"</a>
req=urllib2.Request(url=requrl,data=test_data_urlencode)
printreq
res_data=urllib2.urlopen(req)
res=res_data.read()
printres

方法二、
importurllib
importhttplib
test_data={'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode=urllib.urlencode(test_data)
requrl="<ahref="http://192.168.81.16/cgi-bin/python_test/test.py""target="_blank">http://192.168.81.16/cgi-bin/python_test/test.py"</a>
headerdata={"Host":"192.168.81.16"}
conn=httplib.HTTPConnection("192.168.81.16")
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers=headerdata)
response=conn.getresponse()
res=response.read()
printres

Ⅹ python httplib怎麼列印發送的請求

python有一個httplib的庫,提供了很方便的方法實現GET和POST請求,只需要簡單的組織一下即可。
python發送get請求代碼:

#!/usr/bin/env python
#coding=utf8

import httplib

httpClient = None

try:
httpClient = httplib.HTTPConnection('localhost', 80, timeout=30)
httpClient.request('GET', '/test.php')

#response是HTTPResponse對象
response = httpClient.getresponse()
print response.status
print response.reason
print response.read()
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()

發送POST請求

#!/usr/bin/env python
#coding=utf8

import httplib, urllib

httpClient = None
try:
params = urllib.urlencode({'name': 'tom', 'age': 22})
headers = {"Content-type": "application/x-www-form-urlencoded"
, "Accept": "text/plain"}

httpClient = httplib.HTTPConnection("localhost", 80, timeout=30)
httpClient.request("POST", "/test.php", params, headers)

response = httpClient.getresponse()
print response.status
print response.reason
print response.read()
print response.getheaders() #獲取頭信息
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()

閱讀全文

與pythonhttplib教程相關的資料

熱點內容
同學app在哪裡下載 瀏覽:615
可以投屏的網站影院 瀏覽:431
盲俠楊寡婦扮演者 瀏覽:105
情片網 瀏覽:64
php變慢 瀏覽:11
質數的後代python 瀏覽:149
如何做好美逛App 瀏覽:591
租伺服器租用後怎麼使用 瀏覽:285
木勺解壓助眠視頻 瀏覽:371
酒吧陪女電影 瀏覽:657
雙胞胎兄弟的韓國愛情電影 瀏覽:425
女人遇到網球教練韓國電影 瀏覽:43
一線影院和二線影院 瀏覽:379
韓國電影食物鏈裡面的女主角叫什麼名字? 瀏覽:461
程序員做開發256G夠用嗎 瀏覽:186
c程序編譯的秘密 瀏覽:178
安卓頁面廣告怎麼關閉 瀏覽:666
linux信號量命令 瀏覽:345
父親出門上班兒子和繼母的日本電影 瀏覽:954