一:什么是Requests

Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库
如果你看过上篇文章关于urllib库的使用,你会发现,其实urllib还是非常不方便的,而Requests它会比urllib更加方便,可以节约我们大量的工作。(用了requests之后,你基本都不愿意用urllib了)一句话,requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。

默认安装好python之后,是没有安装requests模块的,需要单独通过pip安装

二:Requests功能详解

实例引入:

import requests

response = requests.get('https://www.baidu.com/')
# 添加编码方式,解决乱码问题
response.encoding=response.apparent_encoding
# response.encoding="utf-8"
print(type(response))
print(response.status_code) # 状态码
print(type(response.text))
print(response.text) # 响应的文本内容
print(response.cookies) # 响应的cookie

各种请求方式:

import requests
requests.get('https://www.baidu.com/') # get
requests.post('http://httpbin.org/post') # 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
# 直接加在url后面
response = requests.get("http://httpbin.org/get?name=germey&age=22")
print(response.text) # 方式二
import requests data = {
'name': 'germey',
'age': 22
}
# 通过params来传递data
response = requests.get("http://httpbin.org/get", params=data)
print(response.text) # 上述两种的结果是相同的,通过params参数传递一个字典内容,从而直接构造url
# 注意:第二种方式通过字典的方式的时候,如果字典中的参数为None则不会添加到url上

解析json

import requests
import json response = requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json()) # 实际上是执行了json.loads(response.text)
print(json.loads(response.text))
print(type(response.json()))

获取二进制数据

import requests

# 获取并打印二进制数据
response = requests.get("https://github.com/favicon.ico")
print(type(response.text), type(response.content))
print(response.text)
print(response.content) # 获取二进制数据并存入文件,通常如视频,图片,音乐等
response = requests.get("https://github.com/favicon.ico")
with open('favicon.ico', 'wb') as f:
f.write(response.content)
f.close()

添加headers

# 有些网站必须要带头部信息才能正常访问
import requests 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'
}
response = requests.get("https://www.zhihu.com/explore", headers=headers)
print(response.text)

基本POST请求

import requests

data = {'name': 'germey', 'age': ''} # 通过字典类型构造
response = requests.post("http://httpbin.org/post", data=data)
print(response.text)

响应

reponse属性

import requests

response = requests.get('http://www.jianshu.com')
print(type(response.status_code), response.status_code) # 状态码
print(type(response.headers), response.headers) # 头信息
print(type(response.cookies), response.cookies) # cookies
print(type(response.url), response.url) # url
print(type(response.history), response.history) # 访问列表

状态码判断:--》状态码大全

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'),

三:requests高级操作

文件上传

import requests
# 通过files参数上传,必须以二进制读取
files = {'file': open('favicon.ico', 'rb')}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)

获取cookie

import requests

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

会话维持

# cookie的一个作用就是可以用于模拟登陆,做会话维持
import requests s = requests.Session() # 通过session对象来维持cookie
s.get('http://httpbin.org/cookies/set/number/123456789')
response = s.get('http://httpbin.org/cookies')
print(response.text)

证书验证

# 现在的很多网站都是https的方式访问,所以这个时候就涉及到证书的问题

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:9743",
"https": "https://127.0.0.1:9743",
}
# 通过proxies来设置代理
response = requests.get("https://www.taobao.com", proxies=proxies)
print(response.status_code) ‘‘‘
# 如果代理需要设置用户名和密码,则将字典改写成
proxies = {
"http":"http://user:password@127.0.0.1:9999"
} # 如果代理是通过sokces这种方式,则需要:
pip install "requests[socks]" # 安装模块
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}
’’’

超时设置

import requests
from requests.exceptions import ReadTimeout
try:
# 通过timeout参数设置超时的时间
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout')

认证设置

# 如果碰到需要认证的网站可以通过requests.auth模块实现
# 方式一
import requests
from requests.auth import HTTPBasicAuth r = requests.get('http://120.27.34.24:9001', auth=HTTPBasicAuth('user', ''))
print(r.status_code) # 方式二
import requests r = requests.get('http://120.27.34.24:9001', auth=('user', ''))
print(r.status_code)

异常处理--》详情--》常用的异常继承关系

import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
try:
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout')
except ConnectionError:
print('Connection error')
except RequestException:
print('Error')

爬虫(三):Requests库的基本使用的更多相关文章

  1. PYTHON 爬虫笔记三:Requests库的基本使用

    知识点一:Requests的详解及其基本使用方法 什么是requests库 Requests库是用Python编写的,基于urllib,采用Apache2 Licensed开源协议的HTTP库,相比u ...

  2. Python爬虫之requests库介绍(一)

    一:Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 ...

  3. 爬虫相关--requests库

    requests的理想:HTTP for Humans 一.八个方法 相比较urllib模块,requests模块要简单很多,但是需要单独安装: 在windows系统下只需要在命令行输入命令 pip ...

  4. Python爬虫之requests库的使用

    requests库 虽然Python的标准库中 urllib模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests宣传是 "HTTP for ...

  5. python爬虫之requests库

    在python爬虫中,要想获取url的原网页,就要用到众所周知的强大好用的requests库,在2018年python文档年度总结中,requests库使用率排行第一,接下来就开始简单的使用reque ...

  6. python网络爬虫之requests库

    Requests库是用Python编写的HTTP客户端.Requests库比urlopen更加方便.可以节约大量的中间处理过程,从而直接抓取网页数据.来看下具体的例子: def request_fun ...

  7. Python爬虫:requests 库详解,cookie操作与实战

    原文 第三方库 requests是基于urllib编写的.比urllib库强大,非常适合爬虫的编写. 安装: pip install requests 简单的爬百度首页的例子: response.te ...

  8. 爬虫入门 requests库

    写在最前的具体资料: https://2.python-requests.org//zh_CN/latest/user/quickstart.html https://www.liaoxuefeng. ...

  9. 【Python爬虫】爬虫利器 requests 库小结

    requests库 Requests 是一个 Python 的 HTTP 客户端库. 支持许多 HTTP 特性,可以非常方便地进行网页请求.网页分析和处理网页资源,拥有许多强大的功能. 本文主要介绍 ...

  10. 爬虫值requests库

    requests简介 简介 Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库 ,使用起来比urllib简洁很多 因为是第三方库, ...

随机推荐

  1. 十分钟快速创建 Spring Cloud 项目

    一般来说,Intelij IDEA 可以通过 Maven Archetype 来快速生成Maven项目,其实 IDEA 集成了 Spring 官方提供的 Spring Initializr,可以非常方 ...

  2. Yii2 redis 使用方法

    /** * 基于 yii2.0 redis使用方法 *///项目根目录命令行执行 composer require --prefer-dist yiisoft/yii2-redis; //在配置文件中 ...

  3. ASCII,UTF-8,Unicode字符串相互转换

    #include<string> #include<windows.h> #include<vector> using namespace std; //utf8 ...

  4. POJ 3233-Matrix Power Series( S = A + A^2 + A^3 + … + A^k 矩阵快速幂取模)

    Matrix Power Series Time Limit: 3000MS   Memory Limit: 131072K Total Submissions: 20309   Accepted:  ...

  5. VC 中的ATL ActiveX 和 MFC ActiveX 有什么区别

    原文转自 https://www.cnblogs.com/zhwl/archive/2012/11/29/2794509.html ATL是ActiveXTemplateLibrary的缩写,它是一套 ...

  6. SVN_06导入项目文档

    把这个项目的文档迁入到SVN Server上的库中 [1]首先右键点击projectAdmin目录,这时候的右键菜单例如以下图看到的:选择copy URL toCLipboard,就是复制统一资源定位 ...

  7. Go 操作 Mysql(一)

    关于 Go 的标准库 database/sql 和 sqlx database/sql 是 Go 操作数据库的标准库之一,它提供了一系列接口方法,用于访问数据库(mysql,sqllite,oralc ...

  8. MySQL-8.0.16 的安装与配置

    最近老是安装mysql, 但是由于各个环境下文件不互通,所以感觉笔记还是记录在这里比较方便.以下内容,是对网络上大家的笔记的搜集和整理,并经过自己的实践,记录下来.以便,让大家更好.更快的配置mysq ...

  9. Linux文件(夹)属性

    ll  或者 ls -lh 查看文件属性:

  10. layui 添加

    {include file="Public:inner_header" /} <link rel="stylesheet" href="__ST ...