简介:Requests是Python HTTP 库,支持Python2.7、Python3+,因结构简单,使用便捷而名声大噪。
帮助文档:
https://docs.python-requests.org/zh_CN/latest/
安装配置:
pip install requests
缺陷不足:不支持http2.0
请求方式:
requests.get('http://httpbin.org/post')
requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')
get不含参数:
import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
get含参数:
import requests
response = requests.get("http://httpbin.org/get?name=tom&age=25")
print(response.text)
get-params的方法:
i
mport requests
data = {
'name': 'tom',
'age': 25
}
response = requests.get("http://httpbin.org/get", params=data)
print(response.text)
解析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()))
获取二进制数据:
import requests
response = requests.get("https://www.baidu.com/favicon.ico")
print(type(response.text), type(response.content))
print(response.text)
print(response.content)
添加headers:
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
}
response = requests.get("https://www.qq.com/", headers=headers)
print(response.text)
post请求:
import requests
data = {'name': 'tom', 'age': '25'}
response = requests.post("http://httpbin.org/post", data=data)
print(response.text)
post请求:请求头headerAccept: application/json, text/plain, /
import requests
data = {'name': 'tom', 'age': '25'}
response = requests.post("http://httpbin.org/post", json=data)
print(response.text)
response属性:
import requests
response = requests.get('http://www.qq.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'> {'Date': 'Mon, 25 Oct 2021 16:38:16 GMT',
# 'Content-Type': 'text/html; charset=GB2312', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive',
# 'Server': 'squid/3.5.24', 'Vary': 'Accept-Encoding, Accept-Encoding, Accept-Encoding',
# 'Expires': 'Mon, 25 Oct 2021 16:39:16 GMT', 'Cache-Control': 'max-age=60',
# 'Content-Encoding': 'gzip', 'X-Cache': 'HIT from shenzhen.qq.com', 'X-Frame-Options': 'SAMEORIGIN',
# 'Content-Security-Policy': 'frame-ancestors https://*.qq.com', 'X-Content-Type-Options': 'nosniff'}
# <class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[]>
# <class 'str'> https://www.qq.com/
# <class 'list'> [<Response [302]>]
常见的网页状态码:
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'),
高阶场景:
1、文件上传
2、获取cookie
3、会话维持、模拟登陆
4、证书验证
5、代理设置
6、超时设置
7、认证设置
高阶场景:文件上传
import requests
files = {'file': open('vite.png', 'rb')}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)
高阶场景:获取cookie
import requests
response = requests.get("https://www.zhihu.com")
print(response.cookies)
for key, value in response.cookies.items():
print(key + '=' + value)
# 执行结果
# <RequestsCookieJar[<Cookie _xsrf=4syf8BxI1p5x3pmf8PVbSvQOui001Lng for .zhihu.com/>]>
# _xsrf=4syf8BxI1p5x3pmf8PVbSvQOui001Lng
高阶场景:会话维持、模拟登陆
import requests
r = requests.get('http://www.baidu.com')
print(r.cookies['BDORZ'])
print(tuple(r.cookies))
高阶场景:证书验证
import requests
from requests.packages import urllib3
urllib3.disable_warnings()
response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)
高阶场景:代理设置
import requests
proxies = {
"http": "http://127.0.0.1:8888",
"https": "https://127.0.0.1:6666",
}
response = requests.get("https://www.baidu.com", proxies=proxies)
print(response.status_code)
高阶场景:超时设置
import requests
from requests.exceptions import ReadTimeout
try:
response = requests.get("http://httpbin.org/get", timeout=0.005)
print(response.status_code)
except ReadTimeout:
print('timeout')
高阶场景:认证设置
import requests
from requests.auth import HTTPBasicAuth
response = requests.get("https://passport.baidu.com/v2/api/?login", auth=HTTPBasicAuth("user", "123"))
print(response.status_code)
小案例:保持会话发送请求。
import random
import time
import datetime
import requests
def make_request(session, body):
resp = session.post('https://accounts.douban.com/j/mobile/login/basic', json=body)
result = resp.text
print(result)
def main():
session = requests.Session()
start = time.time()
for _ in range(100):
now = datetime.datetime.now()
delta = random.randint(5, 15)
ts = (now - datetime.timedelta(days=delta)).strftime('%Y-%m-%d %H:%M:%S')
make_request(session, {'admin': "123456"})
end = time.time()
print(f'发送100次请求,耗时:{end - start}')
if __name__ == '__main__':
main()
微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!