Python Requests模块快速入门
Requests是python的一个HTTP客户端库,跟urllib,urllib2类似。它比urllib更加方便,可以节约我们大量的工作,它比urllib更加Pythoner。
安装Requests
通过pip安装
$pipinstallrequests
或者,下载代码后安装:
$wgethttps://github.com/requests/requests/tarball/master
$mvmasterrequests.tgz
$tarxzfrequests.tgz
$cdrequests-requests-3dc84cd
$pythonsetup.pyinstall
发送请求
使用Requests发送网络请求非常简单。
>>>importrequests#导入Requests模块
>>>result=requests.get('http://www.pythontab.com')#生成Response对象
>>>result.status_code#返回码
200
>>>result.headers['content-type']#返回头部信息
'text/html;charset=utf8'
>>>result.encoding#编码信息
'utf-8'
>>>result.content#内容部分
为URL传递参数
你也许经常想为URL的查询字符串(querystring)传递某种数据。如果你是手工构建URL,那么数据会以键/值对的形式置于URL中,跟在一个问号的后面。例如,www.pythontab.com?version=python3。Requests允许你使用params关键字参数,以一个字典来提供这些参数。举例来说,如果你想传递version=python3和keywords=pythontab到www.pythontab.com,那么你可以使用如下代码:
>>>data={'version':'python3','keywords':'pythontab'}
>>>result=requests.get("http://www.pythontab.com",params=data)
>>>printresult.status_code
200
原始响应内容
在罕见的情况下你可能想获取来自服务器的原始套接字响应,那么你可以访问r.raw。如果你确实想这么干,那请你确保在初始请求中设置了stream=True。具体的你可以这么做:
>>>result=requests.get('http://www.pythontab.com',stream=True)
>>>result.raw
>>>result.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
定制请求头
如果你想为请求添加HTTP头部,只要简单地传递一个dict给headers参数就可以了。
例如,在前一个示例中我们没有指定content-type:
>>>importrequests
>>>url='http://www.pythontab.com'
>>>data={'version':'python3','keywords':'pythontab'}
>>>headers={'content-type':'application/json'}
>>>result=requests.post(url,data=json.dumps(data),headers=headers)
错误与异常
遇到网络问题(如:DNS查询失败、拒绝连接等)时,Requests会抛出一个ConnectionError异常。
遇到罕见的无效HTTP响应时,Requests则会抛出一个HTTPError异常。
若请求超时,则抛出一个Timeout异常。
若请求超过了设定的最大重定向次数,则会抛出一个TooManyRedirects异常。
所有Requests显式抛出的异常都继承自requests.exceptions.RequestException。
其他常用方法
result.content#获取二进制响应内容
result.json()#JSON响应内容
result.headers#响应头内容
result.cookies#cookie内容
result.history#请求历史
以上内容为大家介绍了PythonRequests模块快速入门,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

猜你喜欢LIKE
相关推荐HOT
更多>>
python中的filter函数功能是什么?
python中的filter函数功能是什么?在python中,面对众多的数据,我们要过滤筛选出我们需要的数据。python中的filter函数就是起到了过滤筛选的作...详情>>
2023-11-10 20:37:27
pythontime模块是什么
pythontime模块是什么在python中使用时间,就免不了和time模块打交道,另外两个模块这个暂时先不做介绍。做time模块的使用上,我们可以用它来对...详情>>
2023-11-10 15:53:16
python是什么编程语言
python是什么编程语言1、说明是一种面向对象、解释型计算机程序设计语言,由GuidovanRossum于1989年底发明,第一个公开发行版发行于1991年。Pyt...详情>>
2023-11-10 15:21:05
python异常处理的两种技巧
python异常处理的两种技巧1、传递异常有时我们会在捕捉到一个异常后重新引发它(传递异常),实现起来很简单,使用不带参数的raise语句即可。deff...详情>>
2023-11-10 14:49:39热门推荐
python中的filter函数功能是什么?
沸python delattr函数如何使用?
热python中pdb模块怎么用?
热Python如何截图保存?
新python中缺少module怎么办?
python strftime和strptime的不同分析
python time.strptime的格式化
python中@contextmanager是什么?
python对象的三要素是什么
pythonGIL在Python多线程的应用
python如何对多个CSV文件进行读取
pythonif嵌套命令如何理解?
python对列表进行永久性或临时排序的方法
python生成器调用方法引发异常
技术干货






