爬虫之Requests库
官方文档:http://cn.python-requests.org/zh_CN/latest/
一、引子
import requests
resp = requests.get("https://www.baidu.com/")
print(type(resp)) # <class 'requests.models.Response'>
print(resp.status_code) #
# print(resp.text)
print(type(resp.text)) # <class 'str'>
# print(resp.text)
print(resp.cookies)
各种请求方式:
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 requests
resp = requests.get("http://httpbin.org/get")
print(resp.text)
带参数get请求:
# 方式1
resp = requests.get("http://httpbin.org/get?name=pd&age=18")
print(resp.text)
# 方式2
params = {
"name": "pd",
"age": 18
}
resp = requests.get("http://httpbin.org/get", params=params)
print(resp.text)
解析json:
resp = requests.get("http://httpbin.org/get")
print(resp.json()) # 相当于json.loads(resp.text)
print(type(resp.text)) # <class 'str'>
print(type(resp.json())) # <class 'dict'>
获取二进制数据:
resp = requests.get("https://github.com/favicon.ico")
print(type(resp.text)) # <class 'str'>
print(type(resp.content)) # <class 'bytes'>
print(resp.text)
print(resp.content) # 获取非文本响应内容
with open("favicon.ico", "wb") as f:
f.write(resp.content)
添加请求头:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
}
resp = requests.get("https://www.zhihu.com/explore", headers=headers)
print(resp.text)
POST请求
基本操作:
data = {"name": "pd", "age": 18}
resp = requests.post("http://httpbin.org/post", data=data)
print(resp.text)
添加请求头:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
}
data = {"name": "pd", "age": 18}
resp = requests.post("http://httpbin.org/post", data=data, headers=headers)
print(resp.text)
三、响应
响应属性:
resp = requests.get("https://www.jianshu.com")
print(type(resp.status_code), resp.status_code) # <class 'int'> 200
print(type(resp.headers), resp.headers)
print(type(resp.cookies), resp.cookies) # <class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie locale=zh-CN for www.jianshu.com/>]>
print(type(resp.url), resp.url) # <class 'str'> https://www.jianshu.com/
print(type(resp.history), resp.history) # <class 'list'> []
状态码判断:
resp = requests.get("https://www.jianshu.com")
exit() if not resp.status_code == requests.codes.forbidden else print("403 Forbidden")
response = requests.get("http://www.baidu.com")
exit() if not response.status_code == 200 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',),
# 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',),
# 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'),
状态码信息
四、高级操作
文件上传
files = {"file": open("favicon.ico", "rb")}
resp = requests.post("http://httpbin.org/post", files=files)
print(resp.text)
获取cookie
resp = requests.get("https://www.baidu.com")
print(resp.cookies) # <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
for key, value in resp.cookies.items():
print(key + "=" + value) # BDORZ=27315
会话维持
用来做模拟登录。
requests.get("http://httpbin.org/cookies/set/num/123456") # 设置cookie
resp = requests.get("http://httpbin.org/cookies")
print(resp.text) # {"cookies": {}} cookies为空是因为发起两次请求,而两此请求是完全独立的过程
声明一个session对象发起两次请求:
s = requests.Session()
s.get("http://httpbin.org/cookies/set/num/123456")
resp = s.get("http://httpbin.org/cookies")
print(resp.text) # {"cookies": {"num": "123456"}}
证书验证

如果要爬取上述这种网站的话:
import requests
from requests.packages import urllib3
urllib3.disable_warnings()
resp = requests.get("https://www.xxx.com", verify=False)
print(resp.status_code)
代理设置
proxies = {
"http": "http://127.0.0.1:9743",
"https": "https://127.0.0.1:9743",
}
resp = requests.get("https://www.xxx.com", proxies=proxies)
print(resp.status_code)
如果不是http、https代理,而是socks代理:
pip3 install 'requests[socks]'
proxies = {
"http": "socks5://127.0.0.1:9742",
"https": "socks5://127.0.0.1:9742"
}
response = requests.get("https://www.xxx.com", proxies=proxies)
print(response.status_code)
超时设置
为防止服务器不能及时响应,大部分发至外部服务器的请求都应该带着 timeout 参数。在默认情况下,除非显式指定了 timeout 值,requests 是不会自动进行超时处理的。如果没有 timeout,你的代码可能会挂起若干分钟甚至更长时间。
import requests
from requests import exceptions
try:
resp = requests.get("http://httpbin.org/get", timeout=0.5)
print(resp.status_code)
except exceptions.ReadTimeout:
print("ReadTimeout")
except exceptions.ConnectTimeout:
print("ConnectTimeout")
认证设置

有些网站需要登录才能看到里面的内容:
import requests
from requests.auth import HTTPBasicAuth
resp = requests.get("http://111.11.11.11:9001", auth=HTTPBasicAuth("user", ""))
print(resp.status_code)
异常处理
http://www.python-requests.org/en/master/api/#exceptions
import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
try:
resp = requests.get("http://httpbin.org/get", timeout=0.5)
print(resp.status_code)
except ReadTimeout:
print("Timeout")
except ConnectionError:
print("Connection error")
except RequestException:
print("Error")
爬虫之Requests库的更多相关文章
- Python爬虫之requests库介绍(一)
一:Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 ...
- python爬虫之requests库
在python爬虫中,要想获取url的原网页,就要用到众所周知的强大好用的requests库,在2018年python文档年度总结中,requests库使用率排行第一,接下来就开始简单的使用reque ...
- 爬虫相关--requests库
requests的理想:HTTP for Humans 一.八个方法 相比较urllib模块,requests模块要简单很多,但是需要单独安装: 在windows系统下只需要在命令行输入命令 pip ...
- Python爬虫:requests 库详解,cookie操作与实战
原文 第三方库 requests是基于urllib编写的.比urllib库强大,非常适合爬虫的编写. 安装: pip install requests 简单的爬百度首页的例子: response.te ...
- Python爬虫之requests库的使用
requests库 虽然Python的标准库中 urllib模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests宣传是 "HTTP for ...
- 【Python爬虫】爬虫利器 requests 库小结
requests库 Requests 是一个 Python 的 HTTP 客户端库. 支持许多 HTTP 特性,可以非常方便地进行网页请求.网页分析和处理网页资源,拥有许多强大的功能. 本文主要介绍 ...
- 爬虫值requests库
requests简介 简介 Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库 ,使用起来比urllib简洁很多 因为是第三方库, ...
- (爬虫)requests库
一.requests库简介 urllib库和request库的作用一样,都是服务器发起请求数据,但是requests库比urllib库用起来更方便,它的接口更简单,选用哪种库看自己. 如果没有安装过这 ...
- 【Python爬虫】Requests库的基本使用
Requests库的基本使用 阅读目录 基本的GET请求 带参数的GET请求 解析Json 获取二进制数据 添加headers 基本的POST请求 response属性 文件上传 获取cookie 会 ...
- python网络爬虫之requests库
Requests库是用Python编写的HTTP客户端.Requests库比urlopen更加方便.可以节约大量的中间处理过程,从而直接抓取网页数据.来看下具体的例子: def request_fun ...
随机推荐
- Linux 常用命令大全2
Linux 常用命令大全 [帮助命令] command —help man command man 2 command 查看第2个帮助文件 man -k keyword 查找含有关键字的帮助 info ...
- 基于Spark和Tensorflow构建DCN模型进行CTR预测
实验介绍 数据采用Criteo Display Ads.这个数据一共11G,有13个integer features,26个categorical features. Spark 由于数据比较大,且只 ...
- 17_activity任务栈和启动模式
夜神安卓模拟器. 如果从第一个页面开启另外一个页面,只要不去调finish()方法咱们上一个页面它是不会退出的,它会留在底下.留在底下的话它设计了这样一个模式就是为了维护一个比较好的用户体验,你的仪器 ...
- 如何快速删除Linux下的svn隐藏文件及其他临时文件 (转载)
转自:http://blog.csdn.net/edsam49/article/details/5840489 在Linux下,你的代码工程如果是用svn进行管理的,要删除Linux kernel里的 ...
- 使用 typescript 和 canvas 重构snow效果
前言:之前做过一个 snow 效果,但是是直接用 HTML 做的点击此处查看 ,几个星期前,我用 typescript 和 canvas 重构了一下, snow效果是一个很简单的效果,但是用来练手还是 ...
- 拦截机制中Aspect、ControllerAdvice、Interceptor、Fliter之间的区别详解
Spring中的拦截机制,如果出现异常的话,异常的顺序是从里面到外面一步一步的进行处理,如果到了最外层都没有进行处理的话,就会由tomcat容器抛出异常. 1.过滤器:Filter :可以获得Http ...
- 状压DP UVA 11795 Mega Man's Mission
题目传送门 /* 题意:洛克人有武器可以消灭机器人,还可以从被摧毁的机器人手里得到武器,问消灭全部机器人的顺序总数 状态压缩DP:看到数据只有16,就应该想到状压(并没有).因为是照解题报告写的,代码 ...
- Android 性能优化(16)线程优化:Creating a Manager for Multiple Threads 如何创建一个线程池管理类
Creating a Manager for Multiple Threads 1.You should also read Processes and Threads The previous le ...
- 面向过程与面向对象引入三大特性&&事务
1.面向过程 int a = 10;int b =5;int c = a+b; int r1 = 10;int r2 = 5;double c = r1*r1*3.14 - r2*r2*3.14 缺点 ...
- java IO流技术 之 File
IO流技术 概念:input - output 输入输出流: 输入:将文件读到内存中: 输出:将文件从内存中写出到其他地方 作用:主要就是解决设备和设备之间的数据传输问题. File :文件类的使用十 ...