requests

Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库。因为urllib存在着诸多的不便,而requests的出现能够帮助解决大量的难题。

请求

以get请求为例,一般请求格式为:

import requests
import json
response=requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json())
print(type(response.json()))
print(json.loads(response.text))
print(response.text)
print(response.content)#结果是bytes类型
print(response.content.decode("utf-8"))#转码后以正常的utf-8格式显示

注意:在上面的例子中使用response.text和response.content均打印出了网页的源代码,但是response.content却是以bytes类型显示。此时可以使用decode进行转码即可。

一般当请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 response.text 之时,Requests 会使用其推测的文本编码。

主要请求方式

import requests
url="http://httpbin.org/get"
response1=requests.get(url)#请求指定的页面信息,并返回实体主体。
response2=requests.post(url)
response3=requests.put(url)
response4=requests.delete(url)
response5=requests.head(url)
response6=requests.options(url)

不同请求方式的区别:

GET: 请求指定的页面信息,并返回实体主体。
HEAD: 只请求页面的首部。
POST: 请求服务器接受所指定的文档作为对所标识的URI的新的从属实体。
PUT: 从客户端向服务器传送的数据取代指定的文档的内容。
DELETE: 请求服务器删除指定的页面。
get 和 post比较常见 GET请求将提交的数据放置在HTTP请求协议头中
POST提交的数据则放在实体数据中

基本的get请求

import requests
url="http://httpbin.org/get"
response1=requests.get(url)

带参数的GET请求

import requests
url="http://httpbin.org/get?name=df&age=15"
response=requests.get(url)
print(response.text)

或是这样

import requests
data={
    "name":"df",
    "age":15
}
url="http://httpbin.org/get"
response=requests.get(url,params=data)
print(response.text)

基本的POST 请求

import requests
data={
    "name":"df",
    "age":15
}

response=requests.post("http://httpbin.org/post",data=data)#注意这里一定是"http://httpbin.org/post"而非"http://httpbin.org/get"
print(response.text)

状态码判断

requests访问后,根据response.status_code能够判断访问的状态,主要状态码以及其含义如下:

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', '\\'),
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', '-'),
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
# 图片地址
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
}
url = 'http://img.hb.aicdn.com/494d7bb95fd7338882b009beec454413f168726910c65-e7di7o_fw658'
html = requests.get(url,headers=headers)
with open("1.jpg","wb")as f:
    f.write(html.content)

注意这张图片可以下载下来,但是想下载妹子图上的图片却无法下载,这个暂时还没找到原因。

文件上传

import requests
files={"files":open("timg.jpg","rb")}#注意这里要和这个py文件在同一个文件夹内
response=requests.post("http://httpbin.org/post",files=files)
print(response.text)
response.close()#因为在上传文件的过程中,可能是因为使用urlopen方法太过频繁,引起远程主机的怀疑,被网站认定为是攻击行为。导致urlopen()后,request.read()一直卡死在那里。最后抛出10054异常。所以必须加上这行代码

获取cookies

import requests

response=requests.get("https://www.sogou.com/")
print(response.cookies)
for key,value in response.cookies.items():
    print(key)
    print(key+"="+value)

异常处理

在http://www.python-requests.org/en/master/api/#exceptions中详细列出了众多的exceptions,常用的主要有以下三种:

import requests
from requests.exceptions import ReadTimeout,ConnectionError,RequestException

try:
    response=requests.get("https://www.sogou.com/")
    print(response.status_code)
except ReadTimeout:
    print("Timeout")
except ConnectionError:
    print("Connection Error")
except RequestException:
    print("Request Exception")

 

 

 

posted @ 2019-05-13 22:52  舒畅123  阅读(137)  评论(0编辑  收藏  举报