Python requests库

简介: Python requests库

requests是一个用于在程序中进行http协议下的get和post请求的库。

安装

easy_install requests

或者用

pip install requests

安装好之后在交互模式下运行

>>> import requests
>>> dir(requests)
['ConnectionError', 'HTTPError', 'NullHandler', 'PreparedRequest', 'Request', 'RequestException', 'Response', 'Session', 'Timeout', 'TooManyRedirects', 'URLRequired', '__author__', '__build__', '__builtins__', '__copyright__', '__doc__', '__file__', '__license__', '__name__', '__package__', '__path__', '__title__', '__version__', 'adapters', 'api', 'auth', 'certs', 'codes', 'compat', 'cookies', 'delete', 'exceptions', 'get', 'head', 'hooks', 'logging', 'models', 'options', 'packages', 'patch', 'post', 'put', 'request', 'session', 'sessions', 'status_codes', 'structures', 'utils']

从上面的列表中可以看出在http中常用到的getcookiespost等都赫然在目。

get请求

>>> r = requests.get("http://www.hiekay.com")

得到一个请求的实例然后

>>> r.cookies
<RequestsCookieJar[]>

这个网站对客户端没有写任何cookies内容。换一个看看

>>> r = requests.get("http://www.baidu.com")
>>> r.cookies
<<class 'requests.cookies.RequestsCookieJar'>[Cookie(version=0, name='PHPSESSID', value='buqj70k7f9rrg51emsvatveda2', port=None, port_specified=False, domain='www.baidu.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>

原来这样呀。继续还有别的属性可以看看。

>>> r.headers
{'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Server': 'bfe/1.0.8.18', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:24 GMT', 'Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Date': 'Wed, 16 Jan 2019 07:42:13 GMT', 'Content-Type': 'text/html'}

>>> r.encoding
'UTF-8'

>>> r.status_code
200

下面这个比较长是网页的内容仅仅截取显示部分

>>> print r.text

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç¾åº¦ä¸ä¸ class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ°é»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å°å¾</a>

  ......

请求发出后requests会基于http头部对相应的编码做出有根据的推测当你访问r.text之时requests会使用其推测的文本编码。你可以找出requests使用了什么编码并且能够使用r.coding属性来改变它。

>>> r.content
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> ......

以二进制的方式打开服务器并返回数据。

post请求

requests发送post请求通常你会想要发送一些编码为表单的数据——非常像一个html表单。要实现这个只需要简单地传递一个字典给data参数。你的数据字典在发出请求时会自动编码为表单形式。

>>> import requests
>>> payload = {"key1":"value1","key2":"value2"}
>>> r = requests.post("http://httpbin.org/post")
>>> r1 = requests.post("http://httpbin.org/post", data=payload)

看看效果

image.png

http头部

>>> r.headers['content-type']
'application/json'

注意在引号里面的内容不区分大小写'CONTENT-TYPE'也可以。

还能够自定义头部

>>> r.headers['content-type'] = 'adad'
>>> r.headers['content-type']
'adad'

注意当定制头部的时候如果需要定制的项目有很多需要用到数据类型为字典。

    • *

备注

网上有一个更为详细叙述有关requests模块的网页可以参考http://requests-docs-cn.readthedocs.org/zh_CN/latest/index.html

目录
相关文章
|
5天前
|
网络协议 数据库连接 Python
python知识点100篇系列(17)-替换requests的python库httpx
【10月更文挑战第4天】Requests 是基于 Python 开发的 HTTP 库,使用简单,功能强大。然而,随着 Python 3.6 的发布,出现了 Requests 的替代品 —— httpx。httpx 继承了 Requests 的所有特性,并增加了对异步请求的支持,支持 HTTP/1.1 和 HTTP/2,能够发送同步和异步请求,适用于 WSGI 和 ASGI 应用。安装使用 httpx 需要 Python 3.6 及以上版本,异步请求则需要 Python 3.8 及以上。httpx 提供了 Client 和 AsyncClient,分别用于优化同步和异步请求的性能。
python知识点100篇系列(17)-替换requests的python库httpx
|
12天前
|
存储 网络协议 API
详解Python中的Requests会话管理
详解Python中的Requests会话管理
|
14天前
|
Shell Python
Python 的 os 库的应用实例
Python 的 os 库的应用实例
17 3
|
14天前
|
Linux Python Windows
Python sys 库的应用实例
Python sys 库的应用实例
20 3
|
14天前
|
Python
Python 中的 spell checker 库
Python 中的 spell checker 库
28 1
|
16天前
|
人工智能 搜索推荐 API
使用 Python holidays 库获取中国节日
使用 Python holidays 库获取中国节日
64 2
|
6天前
|
Linux Android开发 开发者
【Python】GUI:Kivy库环境安装与示例
这篇文章介绍了 Kivy 库的安装与使用示例。Kivy 是一个开源的 Python 库,支持多平台开发,适用于多点触控应用。文章详细说明了 Kivy 的主要特点、环境安装方法,并提供了两个示例:一个简单的 Hello World 应用和一个 BMI 计算器界面。
13 0
|
11天前
|
PyTorch 测试技术 算法框架/工具
Python中Thop库的常见用法和代码示例
肆十二在B站分享了关于THOP(Torch-OpCounter)的实战教学视频。THOP是一个用于计算PyTorch模型操作数和计算量的工具,帮助开发者评估模型复杂度和性能。本文介绍了THOP的安装、使用方法及基本用例,包括如何计算模型的FLOPs和参数量。
27 0
|
11天前
|
算法 数据可视化 计算机视觉
Python中医学图像处理常用的库
在Python中,医学图像处理常用的库包括:ITK(及其简化版SimpleITK)、3D Slicer、Pydicom、Nibabel、MedPy、OpenCV、Pillow和Scikit-Image。这些库分别擅长图像分割、配准、处理DICOM和NIfTI格式文件、图像增强及基础图像处理等任务。选择合适的库需根据具体需求和项目要求。
22 0
|
11天前
|
SQL 关系型数据库 MySQL
Python中Pymysql库的常见用法和代码示例
`pymysql` 是一个用于连接 MySQL 数据库的 Python 库,支持 SQL 查询的执行和结果处理。通过 `pip install pymysql` 安装后,可使用 `connect()` 方法建立连接,`cursor()` 创建游标执行查询,包括数据的增删改查,并通过 `commit()` 和 `rollback()` 管理事务,最后需关闭游标和连接以释放资源。
28 0