python_爬虫_requests

导入模块

# 常规导入
import requests

# 用于保持会话
from requests import Session

# 用于认证
from requests.auth import HTTPBasicAuth

请求方式

  • requests.get()
  • requests.post()
  • requests.put()
  • requests.delete()
  • requests.head()
  • requests.options()

get的常用选项

参数说明
headers使用指定头部
params/data设置表单数据
timeout超时设置
proxies使用代理
verify是否验证
auth认证设置

example:

headers={
  'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv2.0.1) Gecko/20100101 Firefox/4.0.1'
  }
data={
  'name':'zzz',
  'age':27
  }

# get
response=requests.get(url="http://httpbin.org/get",headers=headers,params=data,timeout=5)
response=requests.get(url="http://httpbin.org/get?name=zzz&age=23",headers=headers,timeout=5)

# post
response=requests.post(url="http://httpbin.org/post",headers=headers,data=data,timout=5)

# 更多请求方式
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")

# 上传文件
files={'files':open('git.jpg','rb')}
response=requests.post("http://httpbin.org/post",files=files)
print(response.text)

响应体处理

  • response.text:用推导编码解析响应文本
  • response.content:获取二进制响应文本
  • response.json():用json解析响应文本
  • response.encodeing:编码方式
  • response.status_code:状态码
  • response.url:链接
  • response.headers:头部信息
  • response.history:历史
  • response.cookies:cookies
  • requests.utils.get_encodings_from_content(rep.text):查看编码方式

example:

# 修改编码方式
response.encoding='utf-8'
print(response.text)
# ---
print(response.content.decode('utf-8'))

# 解释json
print(json.loads(response.text))
# ---
print(response.json())

#获取cookies
response=requests.get("https://www.baidu.com/")
print(response.cookies)
for key,value in response.cookies.items():
  print(key+'='+value)

保持会话模式

s=requests.Session()
s.get('http://httpbin.org/cookies/set/number/123456',)
response=s.get('http://httpbin.org/cookies',headers=headers)
print(response.text)
response=s.get('http://httpbin.org/cookies')
print(response.text)

设置代理

# 不要账户名
proxies={
  'http':'http://113.121.242.191:808',
  'https':'https://113.121.242.191:808'
}

# 需要账户名
uproxies={
  'http':'http://user:password@113.121.242.191:808',
  'https':'https://user:password@113.121.242.191:808'
}

# sokces方式
sproxies={
  'http':'socks5://113.121.242.191:808',
  'https':'socks5://113.121.242.191:808'
}

response=requests.get('http://httpbin.org/get',proxies=proxies)
print(response.text)

忽略证书

response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)

认证设置

# 方法一
from requests.auth import HTTPBasicAuth
response=requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth('user','123'))
print(response.status_code)

# 方法二
response=requests.get("http://120.27.34.24:9001/",auth=('user','123'))
print(response.status_code)

异常处理

from requests.exceptions import ReadTimeout,ConnectionError,RequestException

try:
  response = requests.get("http://httpbin.org/get",timeout=0.1)
  print(response.status_code)
except ReadTimeout:
  print("timeout")
except ConnectionError:
  print("connection Error")
except RequestException:
  print("error")

其他补充

状态码汇总

常规:

  • 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’),

相关文档

调试网站

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值