7Python标准库系列之requests模块

简介:

Python标准库系列之requests模块


Requests is the only Non-GMO HTTP library for Python, safe for human consumption.

官方文档:http://docs.python-requests.org/en/master/


安装Requests模块

Requests模块官方提供了两种方式安装:

pip方式安装

1
pip install requests

源码方式安装

1
2
3
git clone git: / / github.com / kennethreitz / requests.git
cd requests
python setup.py install

验证是否安装成功

进入python解释的,导入模块试试,如果导入成功则安装成功,否则就需要检查那里执行错误了呢。

1
2
3
4
C:\Users\anshengme> python
Python  3.5 . 1  (v3. 5.1 : 37a07cee5969 , Dec   6  2016 01 : 54 : 25 ) [MSC v. 1900  64  bit (AMD64)] on win32
Type  "help" "copyright" "credits"  or  "license"  for  more information.
>>>  import  requests

环境准备

安装gunicornhttpbin

1
sudo pip3 install gunicorn httpbin

启动一个gunicornServer

1
2
3
4
5
   sudo gunicorn httpbin:app
[ 2016 - 10 - 27  11 : 45 : 08  + 0800 ] [ 12175 ] [INFO] Starting gunicorn  19.6 . 0
[ 2016 - 10 - 27  11 : 45 : 08  + 0800 ] [ 12175 ] [INFO] Listening at: https: / / blog.ansheng.me: 8000  ( 12175 )
[ 2016 - 10 - 27  11 : 45 : 08  + 0800 ] [ 12175 ] [INFO] Using worker: sync
[ 2016 - 10 - 27  11 : 45 : 08  + 0800 ] [ 12178 ] [INFO] Booting worker with pid:  12178

打开浏览器输入``将会得到以下页面,相当于在本地启动一个http server便于学习requests模块

wKiom1kZEOSQbUI3AACSiuo4Ouk316.png

简单的一个requests小程序

下面的一个小程序会通过requests请求'https://blog.ansheng.me:8000/ip'这个URI链接,获取到对应的数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/use/bin/env python3
# _*_ coding:utf-8 _*_
import  requests
 
URL_IP  =  '
  
def  use_params_requests():
     # 参数
     params  =  { 'params1' 'Hello' 'params2' 'World' }
     # 发送请求
     response  =  requests.get(URL_IP, params = params)
     print ( "响应的状态码:" , response.status_code, response.reason)
     print ( "返回的头部:" , response.headers)
     print ( "把返回的数据转换为json:" , response.json())
     print ( "响应的文本:" , response.text)
     
if  __name__  = =  '__main__' :
     use_params_requests()

发送请求

通过GITHUB提供的API获取用户信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/use/bin/env python3
# _*_ coding:utf-8 _*_
import  requests
import  json
 
URL  =  '
  
def  build_uri(endpoint):
     return  '/' .join([URL, endpoint])
     
def  better_print(json_str):
     return  json.dumps(json.loads(json_str), indent = 4 )
     
def  request_method():
     # 获取用户的所有信息
     response  =  requests.get(build_uri( 'users/anshengme' ))
     print (better_print((response.text)))
     
     print ( "\n" )
     
     # 获取用户的邮箱
     response  =  requests.get(build_uri( 'user/emails' ), auth = ( "anshengme.com@gmail.com" "xxxxxx" ))
     print (better_print((response.text)))
     
if  __name__  = =  '__main__' :
     request_method()

带参数的请求

1
2
3
4
5
6
7
8
9
10
11
# 使用params传参
def  params_request():
     response  =  requests.get(build_uri( 'users' ), params = { 'since' 11 })
     print (better_print(response.text))
     print (response.request.headers)
     print (response.url)
     
# 使用json传参方式
def  json_request():
     response  =  requests.get(build_uri( 'user' ), auth = ( "username" "email" ), json = { "name" "asdas" })
     print (better_print(response.text))

异常处理

1
2
3
4
5
6
7
8
9
def  timeout_request():
     try :
         response  =  requests.get(build_uri( 'user/emails' ), timeout = 10 )
         response.raise_for_status()
     except  Exception as e:
         print (e)
     else :
         print (response.text)
         print (response.status_code)

自定义request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from  requests  import  Request, Session
 
def  hard_request():
     =  Session()
     # 创建请求
     headers  =  { 'User-Agent' 'fake1.3.4' }
     req  =  Request( 'GET' , build_uri( 'user/emails' ), auth = ( 'anshengme.com@gmail.com' 'xxxxxx' ), headers = headers)
     prepped  =  req.prepare()
     print ( "请求头》》" , prepped.headers)
     # 发送请求
     resp  =  s.send(prepped)
     print (resp.status_code)
     print (resp.request.headers)
     print (resp.text)

实例

下载图片/文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/use/bin/env python3
# _*_ coding:utf-8 _*_
import  requests
from  contextlib  import  closing
 
# 流传输的模式
def  download_img():
     url  =  "http://www.sinaimg.cn/IT/cr/2016/0331/725124517.jpg"
     # headers = {
     #     'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'}
     # response = requests.get(url, headers=headers, stream=True)
     response  =  requests.get(url, stream = True )
     print (response.status_code, response.reason)
     
     with  open ( 'github.jpg' 'wb' ) as fd:
         for  chunk  in  response.iter_content( 128 ):
             fd.write(chunk)
             
def  download_img_improved():
     url  =  "http://www.sinaimg.cn/IT/cr/2016/0331/725124517.jpg"
     with closing(requests.get(url, stream = True )) as response:
         # 打开并写入文件
         with  open ( 'github1.jpg' 'wb' ) as fd:
             for  chunk  in  response.iter_content( 128 ):
                 fd.write(chunk)
                 
download_img()
download_img_improved()

处理响应的事件钩子

1
2
3
4
5
6
7
8
9
10
11
12
#!/use/bin/env python3
# _*_ coding:utf-8 _*_
import  requests
 
def  get_key_info(response,  * args,  * * kwargs):
     print (response.headers[ "Content-Type" ])
     
def  main():
     requests.get( "https://www.baidu.com" , hooks = dict (response = get_key_info))
     
if  __name__  = =  "__main__" :
     main()









本文转自 Edenwy  51CTO博客,原文链接:http://blog.51cto.com/edeny/1925733,如需转载请自行联系原作者
目录
相关文章
|
11天前
|
缓存 Shell 开发工具
[oeasy]python071_我可以自己做一个模块吗_自定义模块_引入模块_import_diy
本文介绍了 Python 中模块的导入与自定义模块的创建。首先,我们回忆了模块的概念,即封装好功能的部件,并通过导入 `__hello__` 模块实现了输出 "hello world!" 的功能。接着,尝试创建并编辑自己的模块 `my_file.py`,引入 `time` 模块以获取当前时间,并在其中添加自定义输出。
21 4
|
13天前
|
人工智能 自然语言处理 Shell
[oeasy]python070_如何导入模块_导入模块的作用_hello_dunder_双下划线
本文介绍了如何在Python中导入模块及其作用,重点讲解了`__hello__`模块的导入与使用。通过`import`命令可以将外部模块引入当前环境,增强代码功能。例如,导入`__hello__`模块后可输出“Hello world!”。此外,还演示了如何使用`help()`和`dir()`函数查询模块信息,并展示了导入多个模块的方法。最后,通过一个实例,介绍了如何利用`jieba`、`WordCloud`和`matplotlib`模块生成词云图。总结来说,模块是封装好的功能部件,能够简化编程任务并提高效率。未来将探讨如何创建自定义模块。
33 8
|
21天前
|
Web App开发 数据采集 数据安全/隐私保护
Selenium库详解:Python实现模拟登录与反爬限制的进阶指南
Selenium库详解:Python实现模拟登录与反爬限制的进阶指南
|
1月前
|
数据采集 JavaScript Android开发
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
54 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
2月前
|
测试技术 Python
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
154 31
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
|
2月前
|
机器学习/深度学习 存储 数据挖掘
Python图像处理实用指南:PIL库的多样化应用
本文介绍Python中PIL库在图像处理中的多样化应用,涵盖裁剪、调整大小、旋转、模糊、锐化、亮度和对比度调整、翻转、压缩及添加滤镜等操作。通过具体代码示例,展示如何轻松实现这些功能,帮助读者掌握高效图像处理技术,适用于图片美化、数据分析及机器学习等领域。
91 20
|
2月前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
40 3

热门文章

最新文章