当前位置:首页 » 编程语言 » pythonhttplib2

pythonhttplib2

发布时间: 2022-06-09 23:06:41

python怎样用httplib2来POST多个值

#-*-coding:utf-8-*-
fromurllibimporturlencode
importhttplib2

data={"name":"zhangsan","age":10}
h=httplib2.Http()
resp,content=h.request("www..com","POST",urlencode(data))
printcontent

如果解决了您的问题请采纳!
如果未解决请继续追问

Ⅱ 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十大必学模块是什么

这个不能一概而论的,据说python目前高达27万+个库,看你学习的方向必学模块也有不同,简单列举:

1、网络通用方面:

  • urllib-网络库

  • requests-网络库

  • pycurl– 网络库

  • httplib2– 网络库

  • RoboBrowser– 浏览网页

  • MechanicalSoup-一个与网站自动交互Python库

  • socket– 底层网络接口

    2、爬虫方面:

  • grab– 爬虫框架

  • scrapy– 网络爬虫框架,不支持Python3

  • pyspider–爬虫系统。

  • cola– 爬虫框架

  • portia– 可视化爬虫

  • 3、HTML/XML解析方面:

  • lxml– 高效HTML/ XML处理库

  • cssselect– 解析DOM树和CSS选择器。

  • pyquery– 解析DOM树和jQuery选择器。

  • html5lib– 根据WHATWG规范生成HTML/ XML文档的DOM

  • feedparser– 解析RSS/ATOM feeds。

  • MarkupSafe– 为XML/HTML/XHTML提供了安全转义的字符串。

  • xhtml2pdf– 将HTML/CSS转换为PDF。

  • untangle– XML文件转Python对象

  • 4、文件处理方面:

  • xpinyin– 将中国汉字转为拼音

  • tablib– 数据导出为XLS、CSV、JSON、等格式的模块

  • textract– 从文件中提取文本

  • messytables– 解析表格数据

  • rows– 常用数据接口

  • Office

  • python-docx– 读取,查询和修改docx文件

  • xlwt/xlrd– 从Excel文件读取写入数据和格式信息

  • PDF

  • Markdown

  • Python-Markdown– 一个用Python实现的John Gruber的Markdown。

Ⅳ python http 连接问题,urllib2和httplib2

都没把问题描述清楚,相帮也帮不了。

Ⅳ 求一个Python工具中httplib2库的详细说明

https://github.com/jcgregorio/httplib2 lib库主页

Ⅵ python爬虫需要安装哪些库

一、 请求库

1. requests
requests 类库是第三方库,比 Python 自带的 urllib 类库使用方便和

2. selenium
利用它执行浏览器动作,模拟操作。
3. chromedriver
安装chromedriver来驱动chrome。

4. aiohttp
aiohttp是异步请求库,抓取数据时可以提升效率。

二、 解析库
1. lxml
lxml是Python的一个解析库,支持解析HTML和XML,支持XPath的解析方式,而且解析效率非常高。
2. beautifulsoup4
Beautiful Soup可以使用它更方便的从 HTML 文档中提取数据。

3. pyquery
pyquery是一个网页解析库,采用类似jquery的语法来解析HTML文档。
三、 存储
1. mysql
2. mongodb
3. redis
四、 爬虫框架scrapy
Scrapy 是一套异步处理框架,纯python实现的爬虫框架,用来抓取网页内容以及各种图片
需要先安装scrapy基本依赖库,比如lxml、pyOpenSSL、Twisted

Ⅶ Python菜鸟提问,httplib和urllib2有什么区别

httplib包实现http和https协议请求的客户端,通常不直接使用
urllib包和urllib2包基于httplib包之上,提供高层次的抽象,用于处理url请求

Ⅷ 请教个python httplib2传递参数问题

楼主的理解没有问题啊
.
python中函数的实参传递规则是:
标注了参数名的就要按参数名传递,打乱顺序的情况下一定要加参数名,否则会混乱的。
没有缺省的实参情况下就会依次传递,如果不够的话,后面的会自动去取自己的缺省值。
如果实参的数量比

Ⅸ python httplib2 urllib区别

功能上没什么区别吧,httlib2比urllib更进一步把,比如在长链接支持方面,运行速度方面更优越一点儿,适用情况差不多。
个人感觉pycurl更强大一点。

Ⅹ python中ihttplib,httplib2,urllib2在http请求时哪个更快

= time.time()

httplib2.Http().request(url)
t6 = time.time()
http2 = t6-t5

t3 = time.time()
req = httplib.HTTPConnection(com')
req.request('GET', '/')
t4 = time.time()
http = t4-t3


t1 = time.time()
urllib2.urlopen(url)
t2 = time.time()
urll = t2-t1

print http2
print httpprint urll

结果:
0.156999826431
0.0150001049042
0.0780000686646
我写了如上代码测试的时候通常都是httplib的速度较快.实际过程中也是如此吗?还是我测试的不对。还有head请求与get请求,为什么head请求测试的时候感觉并没有节省时间呢。我想写爬虫程序,希望速度能更快。

不知道你做了多少次重复的测试呢,单凭一次的测试结果不说明任何问题,我觉得有以下几点可以说明

  • 抓取网页的时间很多取决于http连接建立和数据传输的时间,所以网络状况的影响很大,如果每次都是重新建立连接,和采用什么python库关系不大

  • urllib3可以复用tcp连接来进行多次http请求,所以可以省掉重新建立tcp的时间;requests会检查是否安装了urllib3。

  • head/get请求的时间取决于你请求的server端是否对这两种请求做了不同的处理,如果没有区分的话,两种请求也就没有区别

热点内容
cfft算法 发布:2025-02-08 04:53:59 浏览:959
极客学院php 发布:2025-02-08 04:52:32 浏览:778
书本编译是什么意思 发布:2025-02-08 04:45:56 浏览:953
淘宝密码账号在哪里看 发布:2025-02-08 04:29:39 浏览:536
描绘四季的美文写一份朗读脚本 发布:2025-02-08 04:29:21 浏览:139
金蝶软件服务器是电脑吗 发布:2025-02-08 04:27:06 浏览:973
linux如何搭建c编译环境 发布:2025-02-08 04:24:49 浏览:822
ps脚本批量处理切图 发布:2025-02-08 04:19:03 浏览:58
iisftp命令 发布:2025-02-08 04:04:39 浏览:455
安卓为什么软件老更新 发布:2025-02-08 03:53:40 浏览:735