#coding:utf-8###get请求#In[4]:importrequestsresponserequests.get(http:news.qq.com)type(res
# coding: utf-8# ## get请求# In[4]:import requests
response = requests.get('http://news.qq.com/')
type(response)# In[5]:response.status_code# In[8]:response.text# In[10]:response.COOKIEs# In[12]:response.encoding# In[15]:response.headers# In[21]:# response.json() # json 格式的数据(eg:dict)# In[38]:response.url# In[34]:# 带参数的get 请求
data = {'name' : 'peerslee','gender' : 'M'
}
response = requests.get('http://httpbin.org/get', params=data)
response.text# In[35]:# 解析json
response = requests.get('http://httpbin.org/get')
response.json()# In[37]:# 二进制数据
response = requests.get('https://www.baidu.com/img/bd_logo1.png')
print(type(response.text), type(response.content))
with open(file='bd_logo.png', mode='wb') as f:f.write(response.content)# ## post 请求# In[27]:payload = {'key1' : 'value1', 'key2' : 'value2'}
'''
User-Agent : 有些服务器或 Proxy 会通过该值来判断是否是浏览器发出的请求
Content-Type : 在使用 REST 接口时,服务器会检查该值,用来确定 HTTP Body 中的内容该怎样解析。
application/xml : 在 XML RPC,如 RESTful/SOAP 调用时使用
application/json : 在 JSON RPC 调用时使用
application/x-www-form-urlencoded : 浏览器提交 Web 表单时使用
使用服务器提供的 RESTful 或 SOAP 服务时: Content-Type 设置错误会导致服务器拒绝服务
'''
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36'
}
response = requests.post('http://httpbin.org/post', data=payload, headers=headers)
response.text# In[29]:# 一个key 对应多个value
payload = [('key1', 'value1'), ('key1', 'value2')]
response = requests.post('http://httpbin.org/post', data=payload)
response.text# In[39]:# 传入一个string 而不是 dict
import json
payload = {'key': 'value'}
response = requests.post('http://httpbin.org/post', data=json.dumps(payload))
response.text# In[53]:# 状态码
'''
# Informational.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'),
'''
response = requests.get('http://news.qq.com/')
print(response.status_code, requests.codes.ok) if response.status_code == requests.codes.ok else print('error')# In[76]:response = requests.get('http://www.jianshu.com/xxx')
print(response.status_code) if response.status_code == requests.codes.not_found else print('error')# In[78]:# 上传文件
files = {'file' : open('bd_logo.png', 'rb')}
response = requests.post('http://httpbin.org/post', files=files)
response.text# In[81]:# 会话,不用维护COOKIE,headers 等
s = requests.Session()
s.get('http://httpbin.org/COOKIEs/set/number/12.35')
s.get('http://httpbin.org/COOKIEs').text# In[86]:# 证书验证
from requests.packages import urllib3
urllib3.disable_warnings() # 消除warning
response = requests.get('http://www.12306.cn/', verify=False) # 虽然已经没有证书错误,但是依然拿他举例
response.status_code# ## 高级用法# In[ ]:'''
1. 代理
2. 超时
3. 认证
4. 异常处理
'''
见官方api "http://docs.python-requests.org/zh_CN/latest/user/advanced.html"
官方文档:高级用法