目前主要写工作中遇到的,如果后续有其他用法,会增加上去。

安装Requests库
进入命令行win+R执行
命令:pip install requests
项目导入:import requests
请求方式
import requests
res1 = requests.post('http://httpbin.org/post')
print(res1.text)
res2 = requests.put('http://httpbin.org/put')
print(res2.text)
res3 = requests.delete('http://httpbin.org/delete')
print(res3.text)
res4 = requests.head('http://httpbin.org/get')
print(res4.text)
res5 = requests.options('http://httpbin.org/get')
print(res5.text)
说明:
GET: 请求指定的页面信息,并返回实体主体。
HEAD: 只请求页面的首部。
POST: 请求服务器接受所指定的文档作为对所标识的URI的新的从属实体。
PUT: 从客户端向服务器传送的数据取代指定的文档的内容。
DELETE: 请求服务器删除指定的页面。
get 和 post比较常见 GET请求将提交的数据放置在HTTP请求协议头中
POST提交的数据则放在实体数据中

两种 HTTP 请求方法:GET 和 POST
在客户机和服务器之间进行请求-响应时,两种最常被用到的方法是:GET 和 POST。
GET - 从指定的资源请求数据。
POST - 向指定的资源提交要被处理的数据
最直观的区别就是GET把参数包含在URL中,POST通过request body传递参数。
基本的GET请求
import requests
res1 = requests.get('http://httpbin.org/get')
print(res1.text)
结果:
import requests
res1 = requests.get('http://httpbin.org/get')
print(res1.text)
带参数的GET请求
import requests
#将name和age传进去
res1 = requests.get('http://httpbin.org/get?name=germey&age=22')
print(res1.text)
#使用params的方法
data = {
'name': 'germey',
'age':22
}
res1 = requests.get('http://httpbin.org/get', params=data)
print(res1.text)
结果:
{
"args": {
"age": "22",
"name": "germey"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.23.0",
"X-Amzn-Trace-Id": "Root=1-5ed4ad86-2274b89bf2c68cfa0e4dbd57"
},
"origin": "121.225.15.128",
"url": "http://httpbin.org/get?name=germey&age=22"
}
解析json
import requests
import json
response = requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json())
print(json.loads(response.text))
print(type(response.json()))
结果:
<class 'str'>
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ed4affa-527fedf72dc7097776cb426b'}, 'origin': '121.225.15.128', 'url': 'http://httpbin.org/get'}
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.23.0', 'X-Amzn-Trace-Id': 'Root=1-5ed4affa-527fedf72dc7097776cb426b'}, 'origin': '121.225.15.128', 'url': 'http://httpbin.org/get'}
<class 'dict'>
获取二进制数据
import requests
response = requests.get("https://github.com/favicon.ico")
print(type(response.text), type(response.content))
print(response.text)
print(response.content)
结果:

添加Headers
有些网站访问时必须带有浏览器等信息,如果不传入headers就会报错,如下:
import requests
response = requests.get("https://www.zhihu.com/explore")
print(response.text)
结果:
<htme>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>openresty</center>
</body>
</html>
当传入headers时:
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
response = requests.get("https://www.zhihu.com/explore", headers=headers)
print(response.text)
结果:

基本post请求
import requests
data = {'name':'germey','age':'22'}
res1 = requests.post("http://httpbin.org/post", data=data)
print(res1.text)
结果:
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "22",
"name": "germey"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "18",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.23.0",
"X-Amzn-Trace-Id": "Root=1-5ed4b476-bd346524b377fd0c86a1b304"
},
"json": null,
"origin": "121.225.15.128",
"url": "http://httpbin.org/post"
}
响应
response响应
import requests
response = requests.get('http://www.baidu.com')
print(type(response.status_code), response.status_code)
print(type(response.headers), response.headers)
print(type(response.cookies), response.cookies)
print(type(response.url), response.url)
print(type(response.history), response.history)
结果:
<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 01 Jun 2020 08:08:45 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:36 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
<class 'str'> http://www.baidu.com/
<class 'list'> []
常见网络状态码:
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication')
高级操作
- 文件上传
使用 Requests 模块,文件的类型会自动进行处理:
import requests
files = {'file': open('test.txt', 'rb')}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)
结果:
{
"args": {},
"data": "",
"files": {
"file": "q\r\ny\r\ny\r\n"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "153",
"Content-Type": "multipart/form-data; boundary=27327811f7f10c4041fdc7239f1b2570",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.23.0",
"X-Amzn-Trace-Id": "Root=1-5ed4b970-edfdb7cc1930c4486d4473c8"
},
"json": null,
"origin": "121.225.15.128",
"url": "http://httpbin.org/post"
}
- 获取cookie
定义:
Cookies是一种能够让网站服务器把少量数据储存到客户端的硬盘或内存,或是从客户端的硬盘读取数据的一种技术。Cookies是当你浏览某网站时,由Web服务器置于你硬盘上的一个非常小的文本文件,它可以记录你的用户ID、密码、浏览过的网页、停留的时间等信息。当你再次来到该网站时,网站通过读取Cookies,得知你的相关信息,就可以做出相应的动作,如在页面显示欢迎你的标语,或者让你不用输入ID、密码就直接登录等等。
用途:
可以利用cookies跟踪统计用户访问该网站的习惯,比如什么时间访问,访问了哪些页面,在每个网页的停留时间等。利用这些信息,一方面是可以为用户提供个性化的服务,另一方面,也可以作为了解所有用户行为的工具,对于网站经营策略的改进有一定参考价值。
当需要cookie时,直接调用response.cookie:
import requests
response = requests.get("https://www.baidu.com")
print(response.cookies)
for key, value in response.cookies.items():
print(key + '=' + value)
结果:
<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ=27315
- 会话维持,模拟登陆
如果某个响应中包含一些Cookie,你可以快速访问它们:
import requests
r = requests.get('http://www.google.com.hk/')
print(r.cookies['NID'])
print(tuple(r.cookies))
要想发送你的cookies到服务器,可以使用 cookies 参数:
import requests
url = 'http://httpbin.org/cookies'cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}
# 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。res1 = requests.get(url, cookies=cookies)
print(res1.json())
结果:
{'cookies': {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}}
- 证书验证
假如因为12306有一个错误证书,我们那它的网站做测试会出现下面的情况,证书不是官方证书,浏览器会识别出一个错误,需要将verify设置为False即可。
import requests
from requests.packages import urllib3
urllib3.disable_warnings()
response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)
结果:
200
- 超时设置
访问有些网站时可能会超时,这时设置好timeout就可以解决这个问题:
import requests
from requests.exceptions import ReadTimeout
try:
res1 = requests.get("http://httpbin.org/get", timeout = 0.5)
print(res1.status_code)
except ReadTimeout:
print('Timeout')
结果返回200

- 认证设置
如果碰到需要认证的网站可以通过requests.auth模块实现
import requests
from requests.auth import HTTPBasicAuth
response = requests.get("http://120.27.34.24:9001/", auth=HTTPBasicAuth("user", "123"))
print(response.status_code)
或者
import requests
response = requests.get("http://120.27.34.24:9001/", auth=("user", "123"))
print(response.status_code)
参考资料
https://blog.csdn.net/byweiker/article/details/79234853