python之爬虫(四)之 Requests库的基本使用

什么是Requests

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

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

requests功能详解

总体功能的一个演示

import requestsresponse  = requests.get("https://www.baidu.com")
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
print(response.content)
print(response.content.decode("utf-8"))
View Code

我们可以看出response使用起来确实非常方便,这里有个问题需要注意一下:
很多情况下的网站如果直接response.text会出现乱码的问题,所以这个使用response.content
这样返回的数据格式其实是二进制格式,然后通过decode()转换为utf-8,这样就解决了通过response.text直接返回显示乱码的问题.

请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 response.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 response.encoding 属性来改变它.如:

response =requests.get("http://www.baidu.com")
response.encoding="utf-8"
print(response.text)

不管是通过response.content.decode("utf-8)的方式还是通过response.encoding="utf-8"的方式都可以避免乱码的问题发生

各种请求方式

requests里提供个各种请求方式

import requests
requests.post("http://httpbin.org/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 requestsresponse = requests.get('http://httpbin.org/get')
print(response.text)

带参数的GET请求,例子1

import requestsresponse = requests.get("http://httpbin.org/get?name=zhaofan&age=23")
print(response.text)

如果我们想要在URL查询字符串传递数据,通常我们会通过httpbin.org/get?key=val方式传递。Requests模块允许使用params关键字传递参数,以一个字典来传递这些参数,例子如下:

import requests
data = {"name":"zhaofan","age":22
}
response = requests.get("http://httpbin.org/get",params=data)
print(response.url)
print(response.text)

上述两种的结果是相同的,通过params参数传递一个字典内容,从而直接构造url
注意:第二种方式通过字典的方式的时候,如果字典中的参数为None则不会添加到url上

解析json

import requests
import jsonresponse = requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json())
print(json.loads(response.text))
print(type(response.json()))

从结果可以看出requests里面集成的json其实就是执行了json.loads()方法,两者的结果是一样的

获取二进制数据

在上面提到了response.content,这样获取的数据是二进制数据,同样的这个方法也可以用于下载图片以及
视频资源

添加headers
和前面我们将urllib模块的时候一样,我们同样可以定制headers的信息,如当我们直接通过requests请求知乎网站的时候,默认是无法访问的

import requests
response =requests.get("https://www.zhihu.com")
print(response.text)

这样会得到如下的错误

因为访问知乎需要头部信息,这个时候我们在谷歌浏览器里输入chrome://version,就可以看到用户代理,将用户代理添加到头部信息

 

import requests
headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}
response =requests.get("https://www.zhihu.com",headers=headers)print(response.text)

这样就可以正常的访问知乎了

基本POST请求

通过在发送post请求时添加一个data参数,这个data参数可以通过字典构造成,这样
对于发送post请求就非常方便

import requestsdata = {"name":"zhaofan","age":23
}
response = requests.post("http://httpbin.org/post",data=data)
print(response.text)

同样的在发送post请求的时候也可以和发送get请求一样通过headers参数传递一个字典类型的数据

响应

我们可以通过response获得很多属性,例子如下

import requestsresponse = requests.get("http://www.baidu.com")
print(type(response.status_code),response.status_code)
print(type(response.headers),response.headers)
print(type(response.cookies),response.cookies)
print(type(response.url),response.url)
print(type(response.history),response.history)

结果如下:

状态码判断
Requests还附带了一个内置的状态码查询对象
主要有如下内容:

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

通过下面例子测试:(不过通常还是通过状态码判断更方便)

import requestsresponse= requests.get("http://www.baidu.com")
if response.status_code == requests.codes.ok:print("访问成功")

requests高级用法

文件上传

实现方法和其他参数类似,也是构造一个字典然后通过files参数传递

import requests
files= {"files":open("git.jpeg","rb")}
response = requests.post("http://httpbin.org/post",files=files)
print(response.text)

结果如下:

获取cookie

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

会话维持

cookie的一个作用就是可以用于模拟登陆,做会话维持

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

这是正确的写法,而下面的写法则是错误的

import requestsrequests.get("http://httpbin.org/cookies/set/number/123456")
response = requests.get("http://httpbin.org/cookies")
print(response.text)

因为这种方式是两次requests请求之间是独立的,而第一次则是通过创建一个session对象,两次请求都通过这个对象访问

证书验证

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

import requestsresponse = requests.get("https:/www.12306.cn")
print(response.status_code)

默认的12306网站的证书是不合法的,这样就会提示如下错误

为了避免这种情况的发生可以通过verify=False
但是这样是可以访问到页面,但是会提示:
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)

解决方法为:

import requests
from requests.packages import urllib3
urllib3.disable_warnings()
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)

这样就不会提示警告信息,当然也可以通过cert参数放入证书路径

代理设置

import requestsproxies= {"http":"http://127.0.0.1:9999","https":"http://127.0.0.1:8888"
}
response  = requests.get("https://www.baidu.com",proxies=proxies)
print(response.text)

如果代理需要设置账户名和密码,只需要将字典更改为如下:
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"
}

超时设置

通过timeout参数可以设置超时的时间

认证设置

如果碰到需要认证的网站可以通过requests.auth模块实现

import requestsfrom requests.auth import HTTPBasicAuthresponse = requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth("user","123"))
print(response.status_code)

当然这里还有一种方式

import requestsresponse = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
print(response.status_code)

异常处理

关于reqeusts的异常在这里可以看到详细内容:
http://www.python-requests.org/en/master/api/#exceptions
所有的异常都是在requests.excepitons中

 

 

从源码我们可以看出RequestException继承IOError,
HTTPError,ConnectionError,Timeout继承RequestionException
ProxyError,SSLError继承ConnectionError
ReadTimeout继承Timeout异常
这里列举了一些常用的异常继承关系,详细的可以看:
http://cn.python-requests.org/zh_CN/latest/_modules/requests/exceptions.html#RequestException

通过下面的例子进行简单的演示

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

其实最后测试可以发现,首先被捕捉的异常是timeout,当把网络断掉的haul就会捕捉到ConnectionError,如果前面异常都没有捕捉到,最后也可以通过RequestExctption捕捉到

转载于:https://www.cnblogs.com/shuai1991/p/10814937.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/277789.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

https://blog.csdn.net/cscscscsc/article/details/50

https://blog.csdn.net/cscscscsc/article/details/50899522转载于:https://blog.51cto.com/7237876/2129682

linux下安装mysql说明

1.msyql下载 mysql-5.6.33 通用版,linux64位,官方下载地址:http://dev.mysql.com/downloads/mysql/5.6.html#downloads。也可以通过命令下载:wget http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.33-linux-glibc2.5-x86…

win8下cocos2dx-3.2+VS2012环境配置及项目创建

这是本人CSDN的第一篇博客,因为假期在学校做实训项目接触到了cocos2dx,觉得是一个特别适用强大,有不错的可移植性(虽然可移植性不错,但实际上写好的游戏往Android上移植,我的队友废了好大劲。。。&#xff…

Android通过透明度设置背景变暗

变暗 WindowManager.LayoutParams lpgetWindow().getAttributes(); lp.alpha0.3f; getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); getWindow().setAttributes(lp);变为原来的样子 WindowManager.LayoutParams lpgetWindow().getAttributes(); lp.alpha1.…

BZOJ4557:[JLOI2016/SHOI2016]侦察守卫——题解

https://www.lydsy.com/JudgeOnline/problem.php?id4557 小R和B神正在玩一款游戏。这款游戏的地图由N个点和N-1条无向边组成,每条无向边连接两个点,且地图是连通的。换句话说,游戏的地图是一棵有N个节点的树。 游戏中有一种道具叫做侦查守卫…

Mac系统下Homebrew的安装和使用Homebrew安装python

这里向大家推荐一个东西,Mac下很好用的东西,叫做Homebrew。刚开始接触Mac的时候,我也没听过这个东西,但装了以后真的觉得,TMD太碉堡了。引用一句话:Homebrew is the easiest and most flexible way to inst…

JS中的深拷贝

前言:我们经常会遇到想要将一个对象为己所用,但又不能污染原对象的需求,这就涉及到了js对象的深拷贝。 比如说在VUE的子组件中,父组件传过来的数据中若是有对象,而子组件需要用父组件的数据进行初始化并且有另做他用的…

Mac下cocos2dx-3.2+Xcode环境配置和项目创建

这是有关环境配置的第二篇教程,第一篇讲的是win8下的环境配置。这里我们使用C。所有如果你用其他语言如Lua和js进行cocos2d开发,那么可以再找一找其他的配置文档。下面要说Mac os 下 cocos2dx-3.2Xcode的环境配置,这里我使用的是Xcode 5.1.1。…

对flex-grow和flex-shrink的深入理解

flex弹性布局,如果子元素宽度之和大于或者小于父元素宽度,空间就会存在剩余和不够,flex默认不换行,除非设置flex-wrap,那么这种情况下,有两个重要的属性,flex-grow和flex-shrink. flex-grow默认值为0&#…

拿下京东榜单第五首战告捷,看联想手机如何上演王者归来

618对于手机行业来说是一个非常重要的日子,京东618上销量的高低在某种程度上就代表了该手机品牌在国内市场的影响力,以及在行业中所处的位置。因此,今年的618各大手机品牌卯足了劲在京东平台上展开较量。荣耀、小米、VIVO、OPPO等手机品牌相继…

Mac OS使用技巧之一:查看Finder中的.bash_profile等系统隐藏文件

作为一个程序员,经常要配置变量,可能要更改hosts文件,或者你闲着没事儿寻找homebrew给你安装的东西在什么地方。Mac OS的内核是Unix,Linux/Unix系统出于系统安全和用户安全的考虑,会把一些与系统相关的文件隐藏&#x…

java.lang.NumberFormatException: For input string: “name”

背景&#xff1a;action中查询出list数据需要在前台进行显示&#xff0c;但根据主键在数据库中查询出的数据list中含有熟悉alist属性为配置表&#xff0c;且支持用户多选&#xff0c;前端通过el表达式显示 前台界面为&#xff1a;<c:forEach items"${list}" var&q…

win8下cocos2dx3.2移植android平台及代码打包APK

cocos2dx程序不能只在VS2012下运行&#xff0c;迟早是要搬运到Android和IOS上的。Windows下移植IOS平台先搁下不说比较困难&#xff0c;而且只有越狱的苹果机才可以运行&#xff0c;而且毕竟IOS高端、小众。这里主要讲一下移植Android&#xff0c;windows下cocos2dx打包成APK和…

【转】用Fiddler做抓包分析详解

1.为什么是Fiddler? 抓包工具有很多&#xff0c;小到最常用的web调试工具firebug&#xff0c;达到通用的强大的抓包工具wireshark.为什么使用fiddler?原因如下&#xff1a; a.Firebug虽然可以抓包&#xff0c;但是对于分析http请求的详细信息&#xff0c;不够强大。模拟http…

读《活着》----余华

这本书所处时代背景尽管与我生活的时代背景不同&#xff0c;但是我仍是被人物的生活所打动。这本书为我们描述了一个拥有一百亩的阔少爷徐福贵因为赌而输掉全部家产&#xff0c;到经历将自己的父亲&#xff0c;母亲&#xff0c;儿子&#xff0c;女儿&#xff0c;女媳&#xff0…

常用数据库连接和diriver以及默认端口

sqlserver默认端口号为&#xff1a;1433 URL:"jdbc:microsoft:sqlserver://localhost:1433;DatabaseNamedbname" DRIVERNAME:"com.microsoft.jdbc.sqlserver.SQLServerDriver"; mysql 默认端口号为&#xff1a;3306 URL:jdbc:mysql://localhost:3306/…

Mac下cocos2dx3.2移植android平台详细教程

本文是cocos2dx移植android的第二篇教程&#xff0c;笔者深深感觉&#xff0c;cocos2dx移植android平台是永远的痛啊。。。下面讲一下笔者花费一个周研究的Mac OS下的cocos2dx3.2android配置首先要准备的东西&#xff08;1&#xff09;下载cocos2dx3.2 http://www.cocos2d-x.o…

robotframework(12)修改用户密码(从数据库查询短信验证码)

一、testcase&#xff1a;修改用户密码需要6个参数&#xff08;短信验证码、设置的新密码、用户已登录的userid及用户唯一标识、接口校验码、被修改的手机号&#xff09;&#xff0c;故先准备这些参数 二、用户登录请求&#xff0c;&#xff08;获取userid、用户唯一标识&#…

Mac OS使用技巧之二:修改变量Path解决android: command not found

前一阵子&#xff0c;一直在搞Mac OS和win8下cocos2dx移植android平台的方法。一步步从无到有的慢慢摸索出来。最近发现了一个小问题&#xff0c;有关环境变量配置的写下来分享给大家。就是我们在windows8下查看已有android SDK的版本&#xff0c;需要在CMD里面输入&#xff1a…

Jenkins架构

一. Master 和slave.下图阐述了master-slave交互的架构&#xff1a;在上面这个分布式的构建环境中&#xff0c;Jenkins master主要负责如下&#xff1a;接收构建触发&#xff08;比如&#xff0c;一个提交到GitHub后&#xff09;发送通知&#xff08;比如&#xff0c;在构建失败…