导航:首页 > 编程语言 > 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教程相关的资料

热点内容
安卓软件没网怎么回事 浏览:785
dvd压缩碟怎么导出电脑 浏览:272
冒险岛什么服务器好玩 浏览:541
如何在服务器上做性能测试 浏览:793
命令序列错 浏览:259
javaif的条件表达式 浏览:576
手机app上传的照片怎么找 浏览:531
云服务器面临哪些威胁 浏览:748
c语言各种编译特点 浏览:177
路由器多种加密方法 浏览:604
程序员阻止电脑自动弹出定位 浏览:168
如何做服务器服务商 浏览:761
su剖切命令 浏览:726
devc编译背景 浏览:211
学习单片机的意义 浏览:51
音频算法AEC 浏览:911
加密货币容易被盗 浏览:82
苹果平板如何开启隐私单个app 浏览:704
空调压缩机一开就停止 浏览:528
如何下载虎牙app 浏览:848