爬虫(三):Requests库的基本使用
一:什么是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库的基本使用的更多相关文章
- PYTHON 爬虫笔记三:Requests库的基本使用
知识点一:Requests的详解及其基本使用方法 什么是requests库 Requests库是用Python编写的,基于urllib,采用Apache2 Licensed开源协议的HTTP库,相比u ...
- Python爬虫之requests库介绍(一)
一:Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 ...
- 爬虫相关--requests库
requests的理想:HTTP for Humans 一.八个方法 相比较urllib模块,requests模块要简单很多,但是需要单独安装: 在windows系统下只需要在命令行输入命令 pip ...
- Python爬虫之requests库的使用
requests库 虽然Python的标准库中 urllib模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests宣传是 "HTTP for ...
- python爬虫之requests库
在python爬虫中,要想获取url的原网页,就要用到众所周知的强大好用的requests库,在2018年python文档年度总结中,requests库使用率排行第一,接下来就开始简单的使用reque ...
- python网络爬虫之requests库
Requests库是用Python编写的HTTP客户端.Requests库比urlopen更加方便.可以节约大量的中间处理过程,从而直接抓取网页数据.来看下具体的例子: def request_fun ...
- Python爬虫:requests 库详解,cookie操作与实战
原文 第三方库 requests是基于urllib编写的.比urllib库强大,非常适合爬虫的编写. 安装: pip install requests 简单的爬百度首页的例子: response.te ...
- 爬虫入门 requests库
写在最前的具体资料: https://2.python-requests.org//zh_CN/latest/user/quickstart.html https://www.liaoxuefeng. ...
- 【Python爬虫】爬虫利器 requests 库小结
requests库 Requests 是一个 Python 的 HTTP 客户端库. 支持许多 HTTP 特性,可以非常方便地进行网页请求.网页分析和处理网页资源,拥有许多强大的功能. 本文主要介绍 ...
- 爬虫值requests库
requests简介 简介 Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库 ,使用起来比urllib简洁很多 因为是第三方库, ...
随机推荐
- Android--Fragment嵌套的问题
项目中遇到Fragment嵌套应用的问题 子Fragment中要用getChildFragmentManager()方法获取FragmentManager,否则会出问题!
- PB笔记之取项次最大值(即使用.describe(" evaluate('ITM_max',0) ") 获取列的最大值) 的条件
dw_1.describe(" evaluate('ITM_max',0) ") :使用 describe 配合 evaluate 取列的最大最小值(或其它表达式)时,必须在数据 ...
- AQS独占式同步队列入队与出队
入队 Node AQS同步队列和等待队列共用同一种节点结构Node,与同步队列相关的属性如下. prev 前驱结点 next 后继节点 thread 入队的线程 入队节点的状态 INITIAl 0 初 ...
- Netty服务端创建流程及组件职责
public class NettyServer { public static void main(String[] args) throws InterruptedException { NioE ...
- VS.NET(C#)--1.4项目与解决方案
项目与解决方案 项目 除创建网站,VS2005可创建项目.然后把项目放入解决方案中.VS2005可编译很多类型项目,分别是: 1.Windows应用程序 --在用戶计算机上运行的客户端应用程序,可显示 ...
- beego 框架基本使用 && 知识点整理
beego 官网的教程已经整理的非常详细了,但作为一个刚接触的学习者,还是有必要做一下整理,这样在后面使用的时候遇到了不太熟悉的地方,还能反过头来看下自己整理的内容,快速的把知识再捞回来,下面是对官网 ...
- Python 练习汇总
1. Python练习_Python初识_day1 2. Python练习_Python初识_day2 3. Python练习_初识数据类型_day3 4. Python练习_数据类型_day4 5. ...
- 0-1背包问题——动态规划求解【Python】
动态规划求解0-1背包问题: 问题:背包大小 w,物品个数 n,每个物品的重量与价值分别对应 w[i] 与 v[i],求放入背包中物品的总价值最大. 动态规划核心:计算并存储小问题的最优解,并将这些最 ...
- PHP原生EXCEL导出带样式无插件无乱码实现
PHP原生EXCEL导出 经测试 带样式 无插件 无乱码,不需要引入任何插件,不需要修改任何编码 (使用时只需要修改引入php数据库配置文件.修改thead tbody中的数据即可.根据自己的需要去接 ...
- sql server存储过程解密
解密存储过程: USE [RYTreasureDB] GO /****** Object: StoredProcedure [dbo].[sp__windbi$decrypt] Script Date ...