requests库详解 --Python3

本文介绍了requests库的基本使用,希望对大家有所帮助。
requests库官方文档:https://2.python-requests.org/en/master/
一、请求:
1、GET请求
coding:utf8
import requests

response = requests.get('http://www.httpbin.org/get')
print(response.text)
2、POST请求
# coding:utf8
import requests

data = {
    'name': 'Thanlon',
    'age': 22,
    'sex': '男'
}
response = requests.post('http://httpbin.org/post', data=data)
print(response.text)
3、解析json
# coding:utf8
import requests, json

response = requests.get('http://www.httpbin.org/get')
print(type(response.text))
# print(response.text)
print(response.json())  # 等价于json.loads(response.text)
print(type(response.json()))
4、获取二进制数据
# coding:utf8
import requests

response = requests.get('https://www.baidu.com/img/dong_5af13a1a6fd9fb2c587e68ca5038a3c8.gif')
print(type(response.text))
print(type(response.content))
print(response.text)
print(response.content)  # 二进制流
5、保存二进制文件(图片、视频)
# coding:utf8
import requests

response = requests.get('https://www.baidu.com/img/dong_5af13a1a6fd9fb2c587e68ca5038a3c8.gif')
with open('image.gif', 'wb') as f:
    f.write(response.content)
    f.close()
6、添加headers(有需要添加请求头信息,否则请求不到,如“知乎”)
# coding:utf8
# get请求,添加headers
import requests

headers = {
    'user-agent': 'Mouser-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36zilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
}
response = requests.get('https://www.zhihu.com/explore', headers=headers)
print(response.text)
#coding:utf8
#post请求,添加headers
import requests

data = {
    'name': 'Thanlon',
    'age': 22,
    'sex': '男'
}
headers = {
    'user-agent': 'Mouser-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36zilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
}
response = requests.post('http://httpbin.org/post', data=data, headers=headers)
print(response.text)
二、响应(response)
1、response相关属性
#coding:utf8
import requests

response = requests.get('http://httpbin.org')
print(type(response.status_code), response.status_code)#状态码 <class 'int'>
print(type(response.headers), response.headers)#响应头 <class 'requests.structures.CaseInsensitiveDict'>
print(type(response.cookies), response.cookies)#cookie <class 'requests.cookies.RequestsCookieJar'>
print(type(response.url), response.url)#请求的url <class 'str'>
print(type(response.history), response.history)  # 访问的历史记录 <class 'list'>
2、状态码判断
#coding:utf8
import requests

response = requests.get('http://httpbin.org')
if not response.status_code == requests.codes.ok:#requests.codes.ok等价于200
    pass
else:
    print('Request Successfully')
3、文件上传
#coding:utf8
import requests

files = {
    'file': open('image.gif', 'rb')  # file可自定义
}
response = requests.post('http://httpbin.org/post', files=files)
print(response.text)
4、获取cookies
#coding:utf8
import requests

response = requests.get('http://www.baidu.com')
print(response.cookies)
print(response.cookies.items())  # [('BDORZ', '27315')]
for key, value in response.cookies.items():
    print(key + '=' + value)

5、会话维持:模拟登录(相当于一个浏览器在请求)
#coding:utf8
import requests

s = requests.Session()
s.get('http://httpbin.org/cookies/set/BDORZ/123456')
response = s.get('http://httpbin.org/cookies')
print(response.text)
6、证书验证
#coding:utf8
import requests
response = requests.get('https://www.12306.cn')
print(response.status_code)
#coding:utf8
import requests, urllib3

urllib3.disable_warnings()  # 消除警报信息
response = requests.get('https://www.12306.cn', verify=False)  # verify默认是True
print(response.status_code)  # 没有进行证书验证,有警报信息,
7、指定证书
#coding:utf8
import requests

response = requests.get('https://www.12306.cn', cert={'/path/server.crt', '/path/key'})
print(response.status_code)
8、代理的设置
#coding:utf8
import requests

proxies = {
    'http': 'http://127.0.0.1:9743',
    'https': 'https://127.0.0.1:9743'
}
response = requests.get('https://www.taobao.com', proxies=proxies)
print(response.status_code)
9、代理的设置(存在用户名和密码的情况下)
#coding:utf8
import requests

proxies = {
    'http': 'http://user:[email protected]:9743',
    'https': 'https://user:[email protected]:9743'
}
response = requests.get('https://www.taobao.com', proxies=proxies)
print(response.status_code)
10、socks代理
import requests

proxies = {
    'http': 'socks5://127.0.0.1:9743',
    'https': 'socks5://127.0.0.1:9743'
}
response = requests.get('https://www.taobao.com', proxies=proxies)
print(response.status_code)
11、超时设置
#coding:utf8
import requests

response = requests.get('http://httpbin.org', timeout=1)
print(response.status_code)
12、认证设置

遇到401错误,即:请求被禁止,需要加上auth参数

#coding:utf8
import requests
from requests.auth import HTTPBasicAuth

response = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
#response = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print(response.status_code)
13、异常处理
#coding:utf8
import requests
from requests.exceptions import ReadTimeout, HTTPError, RequestException, ConnectionError

try:
    response = requests.get('http://httpbin.org', timeout=0.3)
    print(response.status_code)
except ReadTimeout:
    print('Timeout')
except HTTPError:
    print('Http Error')
# except ConnectionError:
#     print('Connection Error')
except RequestException:
    print('Request Error ')

原文地址:https://www.cnblogs.com/qikeyishu/p/10752774.html

时间: 2024-08-27 15:21:21

requests库详解 --Python3的相关文章

python WEB接口自动化测试之requests库详解

1.Get请求 前提: requests库是python的第三方库,需要提前安装哦,可以直接用pip命令:`python –m pip install requests` 按照惯例,先将requests库的属性打印出来,看看哪些属性. >>> import requests >>> dir(requests) #查看requests库的属性 ['ConnectionError', 'HTTPError', 'NullHandler', 'PreparedRequest'

Requests库详解

urllib库作为基本库,requests库也是在urllib库基础上发展的 但是urllib在使用上不如requests便利,比如上篇文章在写urllib库的时候,比如代理设置,处理cookie时,没有写,因为感觉比较繁琐,另外在发送post请求的时候,也是比较繁琐. 一言而代之,requests库是python实现的简单易用的HTTP库 在以后做爬虫的时候,建议用requests,不用urllib 用法讲解: #!/usr/bin/env python # -*- coding:utf-8

Requests实践详解

Requests是什么 Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库 如果你看过上篇文章关于urllib库的使用,你会发现,其实urllib还是非常不方便的,而Requests它会比urllib更加方便,可以节约我们大量的工作.(用了requests之后,你基本都不愿意用urllib了)一句话,requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库. 默认安装好python之后,是没有

详解 Python3 正则表达式系列索引

详解 Python3 正则表达式(一) 详解 Python3 正则表达式(二) 详解 Python3 正则表达式(三) 详解 Python3 正则表达式(四) 详解 Python3 正则表达式(五) 详解 Python3 正则表达式(六) 详解 Python3 正则表达式(七)

详解 Python3 正则表达式(二)

上一篇:详解 Python3 正则表达式(一) 本文翻译自:https://docs.python.org/3.4/howto/regex.html 博主对此做了一些批注和修改 ^_^ 使用正则表达式 现在我们开始来写一些简单的正则表达式吧.Python 通过 re 模块为正则表达式引擎提供一个接口,同时允许你将正则表达式编译成模式对象,并用它们来进行匹配. 批注:re 模块是使用 C 语言编写,所以效率比你用普通的字符串方法要高得多:将正则表达式进行编译(compile)也是为了进一步提高效率

Struts标签库详解【3】

struts2标签库详解 要在jsp中使用Struts2的标志,先要指明标志的引入.通过jsp的代码的顶部加入以下的代码: <%@taglib prefix="s" uri="/struts-tags" %> If elseif  else 描述: 执行基本的条件流转. 参数: 名称 必需 默认 类型 描述 备注 test 是 boolean 决定标志里的内容是否显示的表达式 else标志没有这个参数 id 否 Object/String 用来标识元素的

Lua的协程和协程库详解

我们首先介绍一下什么是协程.然后详细介绍一下coroutine库,然后介绍一下协程的简单用法,最后介绍一下协程的复杂用法. 一.协程是什么? (1)线程 首先复习一下多线程.我们都知道线程——Thread.每一个线程都代表一个执行序列. 当我们在程序中创建多线程的时候,看起来,同一时刻多个线程是同时执行的,不过实质上多个线程是并发的,因为只有一个CPU,所以实质上同一个时刻只有一个线程在执行. 在一个时间片内执行哪个线程是不确定的,我们可以控制线程的优先级,不过真正的线程调度由CPU的调度决定.

详解 Python3 正则表达式(一)

本文翻译自:https://docs.python.org/3.4/howto/regex.html 博主对此做了一些批注和修改 ^_^ 正则表达式介绍 正则表达式(Regular expressions 也称为 REs,或 regexes 或 regex patterns)本质是一个微小的且高度专业化的编程语言.它被嵌入到 Python 中,并通过 re 模块提供给程序员使用.使用正则表达式,你需要指定一些规则来描述那些你希望匹配的字符串集合.这些字符串集合可能包含英语句子.e-mail 地址

详解 Python3 正则表达式(三)

上一篇:详解 Python3 正则表达式(二) 本文翻译自:https://docs.python.org/3.4/howto/regex.html 博主对此做了一些批注和修改 ^_^ 模块级别的函数 使用正则表达式也并非一定要创建模式对象,然后调用它的匹配方法.因为,re 模块同时还提供了一些全局函数,例如 match(),search(),findall(),sub() 等等.这些函数的第一个参数是正则表达式字符串,其他参数跟模式对象同名方法采用一样的参数:返回值也一样,同样是返回 None