1、发送不同的请求

import requests

r = requests.get('https://www.baidu.com/')
r = requests.post('http://httpbin.org/post')
r = requests.put('http://httpbin.org/put')
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')

2、GET请求

import requests

r = requests.get('http://httpbin.org/get')
print(r.text)
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.10.0"
},
"origin": "122.4.215.33",
"url": "http://httpbin.org/get"
}

结果

import requests

data = {
'name': 'germey',
'age': 22
}
r = requests.get("http://httpbin.org/get", params=data)
print(r.text)

带字典参数请求

import requests
import re 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'
}
r = requests.get("https://www.zhihu.com/explore", headers=headers)
pattern = re.compile('explore-feed.*?question_link.*?>(.*?)</a>', re.S)
titles = re.findall(pattern, r.text)
print(titles)

抓取知乎

import requests

r = requests.get("https://github.com/favicon.ico")
with open('favicon.ico', 'wb') as f:
f.write(r.content)

抓取二进制(即文件,图片也是文件)

3、POST请求

import requests

data = {'name': 'germey', 'age': ''}
r = requests.post("http://httpbin.org/post", data=data)
print(r.text)
{
"args": {},
"data": "",
"files": {},
"form": {
"age": "",
"name": "germey"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.10.0"
},
"json": null,
"origin": "182.33.248.131",
"url": "http://httpbin.org/post"
}

4、响应

import requests

r = requests.get('http://www.jianshu.com')
print(type(r.status_code), r.status_code)
print(type(r.headers), r.headers)
print(type(r.cookies), r.cookies)
print(type(r.url), r.url)
print(type(r.history), r.history)
<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'X-Runtime': '0.006363', 'Connection': 'keep-alive', 'Content-Type': 'text/html; charset=utf-8', 'X-Content-Type-Options': 'nosniff', 'Date': 'Sat, 27 Aug 2016 17:18:51 GMT', 'Server': 'nginx', 'X-Frame-Options': 'DENY', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'ETag': 'W/"3abda885e0e123bfde06d9b61e696159"', 'X-XSS-Protection': '1; mode=block', 'X-Request-Id': 'a8a3c4d5-f660-422f-8df9-49719dd9b5d4', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'read_mode=day; path=/, default_font=font2; path=/, _session_id=xxx; path=/; HttpOnly', 'Cache-Control': 'max-age=0, private, must-revalidate'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie _session_id=xxx for www.jianshu.com/>, <Cookie default_font=font2 for www.jianshu.com/>, <Cookie read_mode=day for www.jianshu.com/>]>
<class 'str'> http://www.jianshu.com/
<class 'list'> []

状态码查询对象requests.codes,用于判断状态码

import requests

r = requests.get('http://www.baidu.com')
exit() if not r.status_code == requests.codes.ok else print('Request Successfully')
# 信息性状态码
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',), # 重定向状态码
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 # 客户端错误状态码
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',), # 服务端错误状态码
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 请求的更多相关文章

  1. 第三百二十二节,web爬虫,requests请求

    第三百二十二节,web爬虫,requests请求 requests请求,就是用yhthon的requests模块模拟浏览器请求,返回html源码 模拟浏览器请求有两种,一种是不需要用户登录或者验证的请 ...

  2. web爬虫,requests请求

    requests请求,就是用yhthon的requests模块模拟浏览器请求,返回html源码 模拟浏览器请求有两种,一种是不需要用户登录或者验证的请求,一种是需要用户登录或者验证的请求 一.不需要用 ...

  3. 一 web爬虫,requests请求

    requests请求,就是用python的requests模块模拟浏览器请求,返回html源码 模拟浏览器请求有两种,一种是不需要用户登录或者验证的请求,一种是需要用户登录或者验证的请求 一.不需要用 ...

  4. 1、web爬虫,requests请求

    requests请求,就是用python的requests模块模拟浏览器请求,返回html源码 模拟浏览器请求有两种,一种是不需要用户登录或者验证的请求,一种是需要用户登录或者验证的请求 一.不需要用 ...

  5. 爬虫之requests请求库高级应用

    1.SSL Cert Verification #证书验证(大部分网站都是https) import requests respone=requests.get('https://www.12306. ...

  6. 爬虫之requests请求库

    介绍 #介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requests库发送请求将网页内容下 ...

  7. 解决爬虫浏览器中General显示 Status Code:304 NOT MODIFIED,而在requests请求时出现403被拦截的情况。

    在此,非常感谢 “完美风暴4” 的无私共享经验的精神    在Python爬虫爬取网站时,莫名遇到 浏览器中General显示  Status Code: 304 NOT MODIFIED 而在req ...

  8. 爬虫(一)—— 请求库(一)requests请求库

    目录 requests请求库 爬虫:爬取.解析.存储 一.请求 二.响应 三.简单爬虫 四.requests高级用法 五.session方法(建议使用) 六.selenium模块 requests请求 ...

  9. 爬虫 http原理,梨视频,github登陆实例,requests请求参数小总结

    回顾:http协议基于请求响应的方式,请求:请求首行 请求头{'keys':vales} 请求体 :响应:响应首行,响应头{'keys':'vales'},响应体. import socket soc ...

随机推荐

  1. PCIe基础篇(一)、基础知识扫盲

    1.PCIe:Peripheral Component interconnect Expess,外围组件接口互联,属于第三代IO总线,PCIe的传输速率指的是实际的有效传输速率,为RAW data(原 ...

  2. Elasticsearch7.X 入门学习第四课笔记---- Search API之(Request Body Search 和DSL简介)

    原文:Elasticsearch7.X 入门学习第四课笔记---- Search API之(Request Body Search 和DSL简介) 版权声明:本文为博主原创文章,遵循CC 4.0 BY ...

  3. Thymeleaf运算符和表达式

    字符串拼接 方式一: <span th:text="'当前是第'+${page}+'页 ,共'+${page}+'页'"></span> 方式二: 使用&q ...

  4. MTCNN 人脸检测

    demo.py import cv2 from detection.mtcnn import MTCNN # 检测图片中的人脸 def test_image(imgpath): mtcnn = MTC ...

  5. ARM Cortex-M底层技术(3)—编译内核的原理及其应用

    概述: 当前开发中,我使用的Keil开发工具较多(keil526),故以keil为例进行介绍,其他开发环境大同小异. 1. 编译链接的定义 不管我们编写的代码有多么简单,都必须经过「编译 --> ...

  6. postgresql相关sql集锦

    1.类似于oracle的listagg->string_agg SELECT area_county,)total FROM project_info GROUP BY area_county ...

  7. 打开pycharm提示python已停止工作

    今天遇到一个棘手的问题: 现象:打开pycharm,立刻提示python已停止工作,关掉后还会弹出一个新的,就是永远维持至少一个提醒框在界面的状态 解决过程: 方法一:然后在网上搜解决办法,有一个主流 ...

  8. man VGCREATE

    VGCREATE(8)                                                        VGCREATE(8) NAME/名称       vgcreat ...

  9. chrles设置断点

    1.选择你要断点的接口,右键Breakpoints 2.配置断点接口proxy>Breakpoint settings query设置为* 3.开始断点,重新抓取接口 修改入参.请求头 修改出参 ...

  10. python-Exception异常使用

    Exception #自定义异常类 ,MyInputExcp继承Exception异常 class MyInputExcp(Exception): def __init__(self, lenght, ...