python3网络爬虫系统学习:第二讲 基本库requests(一)
之前,我们学习了基本库urllib的相关用法,但是在网页验证、Cookies处理等方面是比较繁琐的,需要用到Handler并且还需自己构建Opener。requests库的出现很好的解决了这个问题,下面让我们学习一下有关requests的操作。
requests的安装可以直接使用pip install requests安装
此处,小编建议重新安装pip,这样可以在任何目录使用pip,而不需要切换到pip所在目录下才可以使用,重装命令如下:
python -m pip install --upgrade pip --force-reinstall
接下来,进入正式学习
一、基本用法
1.GET请求
GET请求的API如下:
requests.get(url,params=None,**kwargs)
参数详解:
url:请求链接,必填项
params:请求参数(requests接受的可选参数之一,在GET请求中较为常用)
**kwargs:requests接受的可选参数,有params、data、json、headers、cookies、files、auth、timeout、allow_redirects、proxies、verify、stream以及cert。文章末尾小编总结了可选参数含义和用法。
实例应用:
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:66.0) Gecko/20100101 Firefox/66.0'}
data = {
'name': 'germey'
'age': 22}
# 读取网页
url = 'http://httpbin.org/get'
r = requests.get(url, params = params,headers = headers)
print(r.text)
# 读取图片/音频/视频等本质上是二进制的文件
url = 'https://github.com/favicon.ico'
r = requests.get(url, headers = headers)
print(r.content) #r.content返回bytes类型数据
# 图片保存
with open('f.ico', 'wb') as f:
f.write(r.content)
2.POST请求
POST请求API如下:
requests.post(url, data=None, json=None, **kwargs)
参数详解:
url:必填项,访问地址
data:提交的表单数据,常用类型为dict或者str
json:提交表单数据的另一种方式,常用类型为dict或者str
**kwargs:requests接受的可选参数
小编简单的说一下data参数和json参数的区别:
1、不管json是str还是dict,如果不指定headers中的content-type,默认为application/json
2、data为dict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式
3、data为str时,如果不指定content-type,默认为application/json
4、用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式
常见的form表单可以直接使用data参数进行报文提交,而data的对象则是python中的字典类型;而在最新爬虫的过程中遇到了一种payload报文,是一种json格式的报文,因此传入的报文对象也应该是格式的。
应用实例:
import requests
data = {
'name': 'germey',
'age': 22}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:66.0) Gecko/20100101 Firefox/66.0'}
r = requests.post(url, headers=headers, data=data)
print(r.text)
3.响应
在上面的实例中,通过使用text和content获取了响应内容。此外,还有很多方法和属性可以获得响应的其他信息。
status_code——响应状态码
headers——响应头
cookies——响应Cookies
url——响应网址
history——请求历史
4.requests内置状态码对象requests.codes
例如,requests.codes.ok得到状态码200
各状态码对应信息如下:
# 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')
常见错误代码以及错误原因如下:


下面小编介绍一下这些可选参数分别是什么及其其用法:
params:请求参数(在url中显现的),其值可以是字典、列表或者元组
data:发送信息,主要用于POST请求中发送登录表单信息,其值通常为字典、列表或者元组,也可以是字节或者文件对象
json:发送的JSON序列化数据,值当然为JSON格式
headers:请求头,其值为字典数据
cookies:值为字典或者CookieJar对象
files:上传到服务器的文件。值为{'name': file-tuple}的字典以及('filename', fileobj)、('filename', fileobj, 'content_type')或('filename', fileobj, 'content_type', custom_headers)的元组数据。fileobj为文本读取数据,值为open(filename,mode)或者其他文本读取方式;content_type定义给定文件内容类型的字符串;custom_header是dict对象,包含要为文件添加的附加头。
auth:授权元组
timeout:超时设置,其值可以是数值对象也可以是二维元组对象
allow_redirects:重定向设置,默认值为True
proxies:代理设置,其值为{‘协议名’,url}格式的字典
verify:证书认证,其值为bool型,默认为True
stream:如果“False”,则立即下载响应内容。默认为True
cert:添加证书文件,其值可以是String或者tuple。若为string,则为路径字符串;若为tuple,则为证书数据,构成样式为(cert,key)
小编推一下自己新建的公众号,公众号内容更新快,每天定时更新,内容量适中,便于浏览和记忆

python3网络爬虫系统学习:第二讲 基本库requests(一)的更多相关文章
- python3网络爬虫系统学习:第一讲 基本库urllib
在python3中爬虫常用基本库为urllib以及requests 本文主要描述urllib的相关内容 urllib包含四个模块:requests——模拟发送请求 error——异常处理模块 pars ...
- 【网络爬虫入门02】HTTP客户端库Requests的基本原理与基础应用
[网络爬虫入门02]HTTP客户端库Requests的基本原理与基础应用 广东职业技术学院 欧浩源 1.引言 实现网络爬虫的第一步就是要建立网络连接并向服务器或网页等网络资源发起请求.urllib是 ...
- 《Python3 网络爬虫开发实战》学习资料
<Python3 网络爬虫开发实战> 学习资料 百度网盘:https://pan.baidu.com/s/1PisddjC9e60TXlCFMgVjrQ
- 《Python3 网络爬虫开发实战》开发环境配置过程中踩过的坑
<Python3 网络爬虫开发实战>学习资料:https://www.cnblogs.com/waiwai14/p/11698175.html 如何从墙内下载Android Studio: ...
- 转:【Python3网络爬虫开发实战】 requests基本用法
1. 准备工作 在开始之前,请确保已经正确安装好了requests库.如果没有安装,可以参考1.2.1节安装. 2. 实例引入 urllib库中的urlopen()方法实际上是以GET方式请求网页,而 ...
- Python3 网络爬虫(请求库的安装)
Python3 网络爬虫(请求库的安装) 爬虫可以简单分为几步:抓取页面,分析页面和存储数据 在页面爬取的过程中我们需要模拟浏览器向服务器发送请求,所以需要用到一些python库来实现HTTP的请求操 ...
- python学习第二讲,pythonIDE介绍以及配置使用
目录 python学习第二讲,pythonIDE介绍以及配置使用 一丶集成开发环境IDE简介,以及配置 1.简介 2.PyCharm 介绍 3.pycharm 的安装 二丶IDE 开发Python,以 ...
- java网络爬虫基础学习(三)
尝试直接请求URL获取资源 豆瓣电影 https://movie.douban.com/explore#!type=movie&tag=%E7%83%AD%E9%97%A8&sort= ...
- 崔庆才Python3网络爬虫开发实战电子版书籍分享
资料下载地址: 链接:https://pan.baidu.com/s/1WV-_XHZvYIedsC1GJ1hOtw 提取码:4o94 <崔庆才Python3网络爬虫开发实战>高清中文版P ...
随机推荐
- Hadoop Federation联邦
背景概述 单 NameNode 的架构使得 HDFS 在集群扩展性和性能上都有潜在的问题,当集群大到一定程度后,NameNode 进程使用的内存可能会达到上百 G,NameNode 成为了性能的瓶颈. ...
- MongoDB安装步骤
安装C:\Users\Administrator>d:\mongo\bin\mongod -dbpath=D:\ND.Monodb\ND.Monodb.db -logpath=D:\ND.Mon ...
- 个人Hadoop编程代码记录
**WordCount package cn.cpl.recom; import java.io.IOException; import java.util.StringTokenizer; impo ...
- IE浏览器兼容问题(下)——IE6的常见问题
IE6常见兼容性问题 1.盒模型问题 (1)DTD问题 DTD:文档定义类型,规定了要遵循的书写规范. 如果不写DTD,高级浏览器还是可以正常加载,IE6会以怪异模式进行加载. 盒模型:正常应该是外扩 ...
- 二阶SQL注入理解与体会
一:SQL注入分类 SQL注入一般分为两类:一阶SQL注入(普通SQL注入),二阶SQL注入 二:二者进行比较 0x01:一阶SQL注入: 1:一阶SQL注入发生在一个HTTP请求和响应中,对系统的攻 ...
- February 7 2017 Week 6 Tuesday
It does not do to dwell on dreams, and forget to live. 人不能只生活在梦里,只依靠虚幻的东西而忘记了生活. Don't forget to liv ...
- Kubernetes pod里一个特殊的容器:pause-amd64
大家在使用Docker容器或者Kubernetes时,遇到过这个容器么?gcr.io/google_containers/pause-amd64 docker ps的命令返回的结果: [root@k8 ...
- delegate 和 event
delegate 和 event 观察者模式 这里面综合了几本书的资料. 需求 有这么个项目: 需求是这样的: 一个气象站, 有三个传感器(温度, 湿度, 气压), 有一个WeatherData对象, ...
- [转]How to Leak a Context: Handlers & Inner Classes
Consider the following code: public class SampleActivity extends Activity { private final Handler mL ...
- Hibernate双向一对多、双向多对多关联关系中的映射文件怎么写
这里以一对多关联关系为例.以Country类为一端,Competition类为多端. 一个国家可以有多个赛事,但是一个赛事只能属于一个国家. Country类 public class Country ...